Passed
Push — 4 ( 82f096...161e0a )
by Guy
08:10 queued 11s
created

getExtraSavedData()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 15
rs 10
1
<?php
2
3
namespace SilverStripe\Forms\GridField;
4
5
use SilverStripe\Admin\LeftAndMain;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Admin\LeftAndMain was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Control\RequestHandler;
10
use SilverStripe\Forms\CompositeField;
11
use SilverStripe\Forms\FieldList;
12
use SilverStripe\Forms\Form;
13
use SilverStripe\Forms\FormAction;
14
use SilverStripe\Forms\HiddenField;
15
use SilverStripe\Forms\LiteralField;
16
use SilverStripe\ORM\ArrayList;
17
use SilverStripe\ORM\DataObject;
18
use SilverStripe\ORM\FieldType\DBHTMLText;
19
use SilverStripe\ORM\HasManyList;
20
use SilverStripe\ORM\ManyManyList;
21
use SilverStripe\ORM\RelationList;
22
use SilverStripe\ORM\SS_List;
23
use SilverStripe\ORM\ValidationException;
24
use SilverStripe\ORM\ValidationResult;
25
use SilverStripe\View\ArrayData;
26
use SilverStripe\View\HTML;
27
use SilverStripe\View\SSViewer;
28
29
class GridFieldDetailForm_ItemRequest extends RequestHandler
30
{
31
    use GridFieldStateAware;
32
33
    private static $allowed_actions = [
34
        'edit',
35
        'view',
36
        'ItemEditForm'
37
    ];
38
39
    /**
40
     * The default form actions available to this item request
41
     *
42
     * e.g [
43
     *     'showPagination': true,
44
     *     'showAdd': true
45
     * ]
46
     *
47
     * @var array
48
     */
49
    private static $formActions = [];
50
51
    /**
52
     *
53
     * @var GridField
54
     */
55
    protected $gridField;
56
57
    /**
58
     *
59
     * @var GridFieldDetailForm
60
     */
61
    protected $component;
62
63
    /**
64
     * @var DataObject
65
     */
66
    protected $record;
67
68
    /**
69
     * This represents the current parent RequestHandler (which does not necessarily need to be a Controller).
70
     * It allows us to traverse the RequestHandler chain upwards to reach the Controller stack.
71
     *
72
     * @var RequestHandler
73
     */
74
    protected $popupController;
75
76
    /**
77
     *
78
     * @var string
79
     */
80
    protected $popupFormName;
81
82
    /**
83
     * @var String
84
     */
85
    protected $template = null;
86
87
    private static $url_handlers = [
88
        '$Action!' => '$Action',
89
        '' => 'edit',
90
    ];
91
92
    /**
93
     *
94
     * @param GridField $gridField
95
     * @param GridFieldDetailForm $component
96
     * @param DataObject $record
97
     * @param RequestHandler $requestHandler
98
     * @param string $popupFormName
99
     */
100
    public function __construct($gridField, $component, $record, $requestHandler, $popupFormName)
101
    {
102
        $this->gridField = $gridField;
103
        $this->component = $component;
104
        $this->record = $record;
105
        $this->popupController = $requestHandler;
106
        $this->popupFormName = $popupFormName;
107
        parent::__construct();
108
    }
109
110
    public function Link($action = null)
111
    {
112
        return Controller::join_links(
113
            $this->gridField->Link('item'),
114
            $this->record->ID ? $this->record->ID : 'new',
115
            $action
116
        );
117
    }
118
119
    /**
120
     * @param HTTPRequest $request
121
     * @return mixed
122
     */
123
    public function view($request)
124
    {
125
        if (!$this->record->canView()) {
126
            $this->httpError(403, _t(
127
                __CLASS__ . '.ViewPermissionsFailure',
128
                'It seems you don\'t have the necessary permissions to view "{ObjectTitle}"',
129
                ['ObjectTitle' => $this->record->singular_name()]
130
            ));
131
        }
132
133
        $controller = $this->getToplevelController();
134
135
        $form = $this->ItemEditForm();
136
        $form->makeReadonly();
0 ignored issues
show
Bug introduced by
The method makeReadonly() does not exist on SilverStripe\Control\HTTPResponse. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

136
        $form->/** @scrutinizer ignore-call */ 
137
               makeReadonly();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
137
138
        $data = new ArrayData([
139
            'Backlink'     => $controller->Link(),
140
            'ItemEditForm' => $form
141
        ]);
142
        $return = $data->renderWith($this->getTemplates());
143
144
        if ($request->isAjax()) {
145
            return $return;
146
        } else {
147
            return $controller->customise(['Content' => $return]);
148
        }
149
    }
150
151
    /**
152
     * @param HTTPRequest $request
153
     * @return mixed
154
     */
155
    public function edit($request)
156
    {
157
        $controller = $this->getToplevelController();
158
        $form = $this->ItemEditForm();
159
160
        $return = $this->customise([
161
            'Backlink' => $controller->hasMethod('Backlink') ? $controller->Backlink() : $controller->Link(),
0 ignored issues
show
Bug introduced by
The method Backlink() does not exist on SilverStripe\Control\Controller. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

161
            'Backlink' => $controller->hasMethod('Backlink') ? $controller->/** @scrutinizer ignore-call */ Backlink() : $controller->Link(),
Loading history...
162
            'ItemEditForm' => $form,
163
        ])->renderWith($this->getTemplates());
164
165
        if ($request->isAjax()) {
166
            return $return;
167
        } else {
168
            // If not requested by ajax, we need to render it within the controller context+template
169
            return $controller->customise([
170
                // TODO CMS coupling
171
                'Content' => $return,
172
            ]);
173
        }
174
    }
175
176
    /**
177
     * Builds an item edit form.  The arguments to getCMSFields() are the popupController and
178
     * popupFormName, however this is an experimental API and may change.
179
     *
180
     * @todo In the future, we will probably need to come up with a tigher object representing a partially
181
     * complete controller with gaps for extra functionality.  This, for example, would be a better way
182
     * of letting Security/login put its log-in form inside a UI specified elsewhere.
183
     *
184
     * @return Form|HTTPResponse
185
     */
186
    public function ItemEditForm()
187
    {
188
        $list = $this->gridField->getList();
189
190
        if (empty($this->record)) {
191
            $controller = $this->getToplevelController();
192
            $url = $controller->getRequest()->getURL();
193
            $noActionURL = $controller->removeAction($url);
194
            $controller->getResponse()->removeHeader('Location');   //clear the existing redirect
195
            return $controller->redirect($noActionURL, 302);
196
        }
197
198
        // If we are creating a new record in a has-many list, then
199
        // pre-populate the record's foreign key.
200
        if ($list instanceof HasManyList && !$this->record->isInDB()) {
201
            $key = $list->getForeignKey();
202
            $id = $list->getForeignID();
203
            $this->record->$key = $id;
204
        }
205
206
        if (!$this->record->canView()) {
207
            $controller = $this->getToplevelController();
208
            return $controller->httpError(403, _t(
209
                __CLASS__ . '.ViewPermissionsFailure',
210
                'It seems you don\'t have the necessary permissions to view "{ObjectTitle}"',
211
                ['ObjectTitle' => $this->record->singular_name()]
212
            ));
213
        }
214
215
        $fields = $this->component->getFields();
216
        if (!$fields) {
0 ignored issues
show
introduced by
$fields is of type SilverStripe\Forms\FieldList, thus it always evaluated to true.
Loading history...
217
            $fields = $this->record->getCMSFields();
218
        }
219
220
        // If we are creating a new record in a has-many list, then
221
        // Disable the form field as it has no effect.
222
        if ($list instanceof HasManyList && !$this->record->isInDB()) {
223
            $key = $list->getForeignKey();
224
225
            if ($field = $fields->dataFieldByName($key)) {
226
                $fields->makeFieldReadonly($field);
227
            }
228
        }
229
230
        $form = new Form(
231
            $this,
232
            'ItemEditForm',
233
            $fields,
234
            $this->getFormActions(),
235
            $this->component->getValidator()
236
        );
237
238
        $form->loadDataFrom($this->record, $this->record->ID == 0 ? Form::MERGE_IGNORE_FALSEISH : Form::MERGE_DEFAULT);
239
240
        if ($this->record->ID && !$this->record->canEdit()) {
241
            // Restrict editing of existing records
242
            $form->makeReadonly();
243
            // Hack to re-enable delete button if user can delete
244
            if ($this->record->canDelete()) {
245
                $form->Actions()->fieldByName('action_doDelete')->setReadonly(false);
246
            }
247
        } elseif (!$this->record->ID
248
            && !$this->record->canCreate(null, $this->getCreateContext())
249
        ) {
250
            // Restrict creation of new records
251
            $form->makeReadonly();
252
        }
253
254
        // Load many_many extraData for record.
255
        // Fields with the correct 'ManyMany' namespace need to be added manually through getCMSFields().
256
        if ($list instanceof ManyManyList) {
257
            $extraData = $list->getExtraData('', $this->record->ID);
258
            $form->loadDataFrom(['ManyMany' => $extraData]);
259
        }
260
261
        // TODO Coupling with CMS
262
        $toplevelController = $this->getToplevelController();
263
        if ($toplevelController && $toplevelController instanceof LeftAndMain) {
264
            // Always show with base template (full width, no other panels),
265
            // regardless of overloaded CMS controller templates.
266
            // TODO Allow customization, e.g. to display an edit form alongside a search form from the CMS controller
267
            $form->setTemplate([
268
                'type' => 'Includes',
269
                'SilverStripe\\Admin\\LeftAndMain_EditForm',
270
            ]);
271
            $form->addExtraClass('cms-content cms-edit-form center fill-height flexbox-area-grow');
272
            $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
273
            if ($form->Fields()->hasTabSet()) {
274
                $form->Fields()->findOrMakeTab('Root')->setTemplate('SilverStripe\\Forms\\CMSTabSet');
275
                $form->addExtraClass('cms-tabset');
276
            }
277
278
            $form->Backlink = $this->getBackLink();
0 ignored issues
show
Bug Best Practice introduced by
The property Backlink does not exist on SilverStripe\Forms\Form. Since you implemented __set, consider adding a @property annotation.
Loading history...
279
        }
280
281
        $cb = $this->component->getItemEditFormCallback();
282
        if ($cb) {
0 ignored issues
show
introduced by
$cb is of type Closure, thus it always evaluated to true.
Loading history...
283
            $cb($form, $this);
284
        }
285
        $this->extend("updateItemEditForm", $form);
286
        return $form;
287
    }
288
289
    /**
290
     * Build context for verifying canCreate
291
     * @see GridFieldAddNewButton::getHTMLFragments()
292
     *
293
     * @return array
294
     */
295
    protected function getCreateContext()
296
    {
297
        $gridField = $this->gridField;
298
        $context = [];
299
        if ($gridField->getList() instanceof RelationList) {
300
            $record = $gridField->getForm()->getRecord();
301
            if ($record && $record instanceof DataObject) {
0 ignored issues
show
introduced by
$record is always a sub-type of SilverStripe\ORM\DataObject.
Loading history...
302
                $context['Parent'] = $record;
303
            }
304
        }
305
        return $context;
306
    }
307
308
    /**
309
     * @return CompositeField Returns the right aligned toolbar group field along with its FormAction's
310
     */
311
    protected function getRightGroupField()
312
    {
313
        $rightGroup = CompositeField::create()->setName('RightGroup');
314
        $rightGroup->addExtraClass('ml-auto');
315
        $rightGroup->setFieldHolderTemplate(get_class($rightGroup) . '_holder_buttongroup');
316
317
        $previousAndNextGroup = CompositeField::create()->setName('PreviousAndNextGroup');
318
        $previousAndNextGroup->addExtraClass('btn-group--circular mr-2');
319
        $previousAndNextGroup->setFieldHolderTemplate(CompositeField::class . '_holder_buttongroup');
320
321
        /** @var GridFieldDetailForm $component */
322
        $component = $this->gridField->getConfig()->getComponentByType(GridFieldDetailForm::class);
323
        $paginator = $this->getGridField()->getConfig()->getComponentByType(GridFieldPaginator::class);
324
        $gridState = $this->getStateManager()->getStateFromRequest($this->gridField, $this->getRequest());
325
        if ($component && $paginator && $component->getShowPagination()) {
0 ignored issues
show
introduced by
$paginator is of type SilverStripe\Forms\GridField\GridFieldComponent, thus it always evaluated to true.
Loading history...
326
            $previousIsDisabled = !$this->getPreviousRecordID();
327
            $nextIsDisabled = !$this->getNextRecordID();
328
329
            $previousAndNextGroup->push(
330
                LiteralField::create(
331
                    'previous-record',
332
                    HTML::createTag($previousIsDisabled ? 'span' : 'a', [
333
                        'href' => $previousIsDisabled ? '#' : $this->getEditLink($this->getPreviousRecordID()),
334
                        'data-grid-state' => $gridState,
335
                        'title' => _t(__CLASS__ . '.PREVIOUS', 'Go to previous record'),
336
                        'aria-label' => _t(__CLASS__ . '.PREVIOUS', 'Go to previous record'),
337
                        'class' => 'btn btn-secondary font-icon-left-open action--previous discard-confirmation'
338
                            . ($previousIsDisabled ? ' disabled' : ''),
339
                    ])
340
                )
341
            );
342
343
            $previousAndNextGroup->push(
344
                LiteralField::create(
345
                    'next-record',
346
                    HTML::createTag($nextIsDisabled ? 'span' : 'a', [
347
                        'href' => $nextIsDisabled ? '#' : $this->getEditLink($this->getNextRecordID()),
348
                        'data-grid-state' => $gridState,
349
                        'title' => _t(__CLASS__ . '.NEXT', 'Go to next record'),
350
                        'aria-label' => _t(__CLASS__ . '.NEXT', 'Go to next record'),
351
                        'class' => 'btn btn-secondary font-icon-right-open action--next discard-confirmation'
352
                            . ($nextIsDisabled ? ' disabled' : ''),
353
                    ])
354
                )
355
            );
356
        }
357
358
        $rightGroup->push($previousAndNextGroup);
359
360
        if ($component && $component->getShowAdd() && $this->record->canCreate()) {
361
            $rightGroup->push(
362
                LiteralField::create(
363
                    'new-record',
364
                    HTML::createTag('a', [
365
                        'href' => Controller::join_links($this->gridField->Link('item'), 'new'),
366
                        'data-grid-state' => $gridState,
367
                        'title' => _t(__CLASS__ . '.NEW', 'Add new record'),
368
                        'aria-label' => _t(__CLASS__ . '.NEW', 'Add new record'),
369
                        'class' => 'btn btn-primary font-icon-plus-thin btn--circular action--new discard-confirmation',
370
                    ])
371
                )
372
            );
373
        }
374
375
        return $rightGroup;
376
    }
377
378
    /**
379
     * Build the set of form field actions for this DataObject
380
     *
381
     * @return FieldList
382
     */
383
    protected function getFormActions()
384
    {
385
        $manager = $this->getStateManager();
386
387
        $actions = FieldList::create();
388
        $majorActions = CompositeField::create()->setName('MajorActions');
389
        $majorActions->setFieldHolderTemplate(get_class($majorActions) . '_holder_buttongroup');
390
        $actions->push($majorActions);
391
392
        if ($this->record->ID !== 0) { // existing record
393
            if ($this->record->canEdit()) {
394
                $noChangesClasses = 'btn-outline-primary font-icon-tick';
395
                $majorActions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Save', 'Save'))
396
                    ->addExtraClass($noChangesClasses)
397
                    ->setAttribute('data-btn-alternate-add', 'btn-primary font-icon-save')
398
                    ->setAttribute('data-btn-alternate-remove', $noChangesClasses)
399
                    ->setUseButtonTag(true)
400
                    ->setAttribute('data-text-alternate', _t('SilverStripe\\CMS\\Controllers\\CMSMain.SAVEDRAFT', 'Save')));
401
            }
402
403
            if ($this->record->canDelete()) {
404
                $actions->insertAfter('MajorActions', FormAction::create('doDelete', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete', 'Delete'))
405
                    ->setUseButtonTag(true)
406
                    ->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action--delete'));
407
            }
408
409
            $gridState = $manager->getStateFromRequest($this->gridField, $this->getRequest());
410
            $this->gridField->getState(false)->setValue($gridState);
411
            $actions->push(HiddenField::create($manager->getStateKey($this->gridField), null, $gridState));
412
413
            $actions->push($this->getRightGroupField());
414
        } else { // adding new record
415
            //Change the Save label to 'Create'
416
            $majorActions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Create', 'Create'))
417
                ->setUseButtonTag(true)
418
                ->addExtraClass('btn-primary font-icon-plus-thin'));
419
420
            // Add a Cancel link which is a button-like link and link back to one level up.
421
            $crumbs = $this->Breadcrumbs();
422
            if ($crumbs && $crumbs->count() >= 2) {
423
                $oneLevelUp = $crumbs->offsetGet($crumbs->count() - 2);
424
                $text = sprintf(
425
                    "<a class=\"%s\" href=\"%s\">%s</a>",
426
                    "crumb btn btn-secondary cms-panel-link", // CSS classes
427
                    $oneLevelUp->Link, // url
0 ignored issues
show
Bug Best Practice introduced by
The property Link does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
428
                    _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.CancelBtn', 'Cancel') // label
429
                );
430
                $actions->insertAfter('MajorActions', new LiteralField('cancelbutton', $text));
431
            }
432
        }
433
434
        $this->extend('updateFormActions', $actions);
435
436
        return $actions;
437
    }
438
439
    /**
440
     * Traverse the nested RequestHandlers until we reach something that's not GridFieldDetailForm_ItemRequest.
441
     * This allows us to access the Controller responsible for invoking the top-level GridField.
442
     * This should be equivalent to getting the controller off the top of the controller stack via Controller::curr(),
443
     * but allows us to avoid accessing the global state.
444
     *
445
     * GridFieldDetailForm_ItemRequests are RequestHandlers, and as such they are not part of the controller stack.
446
     *
447
     * @return Controller
448
     */
449
    protected function getToplevelController()
450
    {
451
        $c = $this->popupController;
452
        while ($c && $c instanceof GridFieldDetailForm_ItemRequest) {
453
            $c = $c->getController();
454
        }
455
        return $c;
456
    }
457
458
    protected function getBackLink()
459
    {
460
        // TODO Coupling with CMS
461
        $backlink = '';
462
        $toplevelController = $this->getToplevelController();
463
        if ($toplevelController && $toplevelController instanceof LeftAndMain) {
464
            if ($toplevelController->hasMethod('Backlink')) {
465
                $backlink = $toplevelController->Backlink();
466
            } elseif ($this->popupController->hasMethod('Breadcrumbs')) {
467
                $parents = $this->popupController->Breadcrumbs(false);
0 ignored issues
show
Bug introduced by
The method Breadcrumbs() does not exist on SilverStripe\Control\RequestHandler. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

467
                /** @scrutinizer ignore-call */ 
468
                $parents = $this->popupController->Breadcrumbs(false);
Loading history...
468
                if ($parents && $parents = $parents->items) {
469
                    $backlink = array_pop($parents)->Link;
470
                }
471
            }
472
        }
473
        if (!$backlink) {
474
            $backlink = $toplevelController->Link();
475
        }
476
477
        return $backlink;
478
    }
479
480
    /**
481
     * Get the list of extra data from the $record as saved into it by
482
     * {@see Form::saveInto()}
483
     *
484
     * Handles detection of falsey values explicitly saved into the
485
     * DataObject by formfields
486
     *
487
     * @param DataObject $record
488
     * @param SS_List $list
489
     * @return array List of data to write to the relation
490
     */
491
    protected function getExtraSavedData($record, $list)
492
    {
493
        // Skip extra data if not ManyManyList
494
        if (!($list instanceof ManyManyList)) {
495
            return null;
496
        }
497
498
        $data = [];
499
        foreach ($list->getExtraFields() as $field => $dbSpec) {
500
            $savedField = "ManyMany[{$field}]";
501
            if ($record->hasField($savedField)) {
502
                $data[$field] = $record->getField($savedField);
503
            }
504
        }
505
        return $data;
506
    }
507
508
    public function doSave($data, $form)
509
    {
510
        $isNewRecord = $this->record->ID == 0;
511
512
        // Check permission
513
        if (!$this->record->canEdit()) {
514
            $this->httpError(403, _t(
515
                __CLASS__ . '.EditPermissionsFailure',
516
                'It seems you don\'t have the necessary permissions to edit "{ObjectTitle}"',
517
                ['ObjectTitle' => $this->record->singular_name()]
518
            ));
519
            return null;
520
        }
521
522
        // Save from form data
523
        $this->saveFormIntoRecord($data, $form);
524
525
        $link = '<a href="' . $this->Link('edit') . '">"'
526
            . htmlspecialchars($this->record->Title, ENT_QUOTES)
527
            . '"</a>';
528
        $message = _t(
529
            'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Saved',
530
            'Saved {name} {link}',
531
            [
532
                'name' => $this->record->i18n_singular_name(),
533
                'link' => $link
534
            ]
535
        );
536
537
        $form->sessionMessage($message, 'good', ValidationResult::CAST_HTML);
538
539
        // Redirect after save
540
        return $this->redirectAfterSave($isNewRecord);
541
    }
542
543
    /**
544
     * Gets the edit link for a record
545
     *
546
     * @param  int $id The ID of the record in the GridField
547
     * @return string
548
     */
549
    public function getEditLink($id)
550
    {
551
        $link = Controller::join_links(
552
            $this->gridField->Link(),
553
            'item',
554
            $id
555
        );
556
557
        return $this->getStateManager()->addStateToURL($this->gridField, $link);
558
    }
559
560
    /**
561
     * @param int $offset The offset from the current record
562
     * @return int|bool
563
     */
564
    private function getAdjacentRecordID($offset)
565
    {
566
        $gridField = $this->getGridField();
567
        $list = $gridField->getManipulatedList();
568
        $state = $gridField->getState(false);
569
        $gridStateStr = $this->getStateManager()->getStateFromRequest($this->gridField, $this->getRequest());
570
        if (!empty($gridStateStr)) {
571
            $state->setValue($gridStateStr);
572
        }
573
        $data = $state->getData();
574
        $paginator = $data->getData('GridFieldPaginator');
575
        if (!$paginator) {
576
            return false;
577
        }
578
579
        $currentPage = $paginator->getData('currentPage');
580
        $itemsPerPage = $paginator->getData('itemsPerPage');
581
582
        $limit = $itemsPerPage + 2;
583
        $limitOffset = max(0, $itemsPerPage * ($currentPage-1) -1);
584
585
        $map = $list->limit($limit, $limitOffset)->column('ID');
0 ignored issues
show
Bug introduced by
The method limit() does not exist on SilverStripe\ORM\SS_List. It seems like you code against a sub-type of said class. However, the method does not exist in SilverStripe\ORM\Sortable or SilverStripe\ORM\Filterable. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

585
        $map = $list->/** @scrutinizer ignore-call */ limit($limit, $limitOffset)->column('ID');
Loading history...
586
        $index = array_search($this->record->ID, $map);
587
        return isset($map[$index+$offset]) ? $map[$index+$offset] : false;
588
    }
589
590
    /**
591
     * Gets the ID of the previous record in the list.
592
     *
593
     * @return int
594
     */
595
    public function getPreviousRecordID()
596
    {
597
        return $this->getAdjacentRecordID(-1);
598
    }
599
600
    /**
601
     * Gets the ID of the next record in the list.
602
     *
603
     * @return int
604
     */
605
    public function getNextRecordID()
606
    {
607
        return $this->getAdjacentRecordID(1);
608
    }
609
610
    /**
611
     * Response object for this request after a successful save
612
     *
613
     * @param bool $isNewRecord True if this record was just created
614
     * @return HTTPResponse|DBHTMLText
615
     */
616
    protected function redirectAfterSave($isNewRecord)
617
    {
618
        $controller = $this->getToplevelController();
619
        if ($isNewRecord) {
620
            return $controller->redirect($this->Link());
621
        } elseif ($this->gridField->getList()->byID($this->record->ID)) {
0 ignored issues
show
Bug introduced by
The method byID() does not exist on SilverStripe\ORM\SS_List. It seems like you code against a sub-type of said class. However, the method does not exist in SilverStripe\ORM\Sortable or SilverStripe\ORM\Limitable. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

621
        } elseif ($this->gridField->getList()->/** @scrutinizer ignore-call */ byID($this->record->ID)) {
Loading history...
622
            // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
623
            // to the same URL (it assumes that its content is already current, and doesn't reload)
624
            return $this->edit($controller->getRequest());
625
        } else {
626
            // Changes to the record properties might've excluded the record from
627
            // a filtered list, so return back to the main view if it can't be found
628
            $url = $controller->getRequest()->getURL();
629
            $noActionURL = $controller->removeAction($url);
630
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
631
            return $controller->redirect($noActionURL, 302);
632
        }
633
    }
634
635
    public function httpError($errorCode, $errorMessage = null)
636
    {
637
        $controller = $this->getToplevelController();
638
        return $controller->httpError($errorCode, $errorMessage);
639
    }
640
641
    /**
642
     * Loads the given form data into the underlying dataobject and relation
643
     *
644
     * @param array $data
645
     * @param Form $form
646
     * @throws ValidationException On error
647
     * @return DataObject Saved record
648
     */
649
    protected function saveFormIntoRecord($data, $form)
650
    {
651
        $list = $this->gridField->getList();
652
653
        // Check object matches the correct classname
654
        if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) {
655
            $newClassName = $data['ClassName'];
656
            // The records originally saved attribute was overwritten by $form->saveInto($record) before.
657
            // This is necessary for newClassInstance() to work as expected, and trigger change detection
658
            // on the ClassName attribute
659
            $this->record->setClassName($this->record->ClassName);
660
            // Replace $record with a new instance
661
            $this->record = $this->record->newClassInstance($newClassName);
662
        }
663
664
        // Save form and any extra saved data into this dataobject.
665
        // Set writeComponents = true to write has-one relations / join records
666
        $form->saveInto($this->record);
667
        // https://github.com/silverstripe/silverstripe-assets/issues/365
668
        $this->record->write();
669
        $this->extend('onAfterSave', $this->record);
670
671
        $extraData = $this->getExtraSavedData($this->record, $list);
672
        $list->add($this->record, $extraData);
0 ignored issues
show
Unused Code introduced by
The call to SilverStripe\ORM\SS_List::add() has too many arguments starting with $extraData. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

672
        $list->/** @scrutinizer ignore-call */ 
673
               add($this->record, $extraData);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
673
674
        return $this->record;
675
    }
676
677
    /**
678
     * @param array $data
679
     * @param Form $form
680
     * @return HTTPResponse
681
     * @throws ValidationException
682
     */
683
    public function doDelete($data, $form)
684
    {
685
        $title = $this->record->Title;
686
        if (!$this->record->canDelete()) {
687
            throw new ValidationException(
688
                _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.DeletePermissionsFailure', "No delete permissions")
689
            );
690
        }
691
        $this->record->delete();
692
693
        $message = _t(
694
            'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Deleted',
695
            'Deleted {type} {name}',
696
            [
697
                'type' => $this->record->i18n_singular_name(),
698
                'name' => htmlspecialchars($title, ENT_QUOTES)
699
            ]
700
        );
701
702
        $toplevelController = $this->getToplevelController();
703
        if ($toplevelController && $toplevelController instanceof LeftAndMain) {
704
            $backForm = $toplevelController->getEditForm();
0 ignored issues
show
Bug introduced by
The method getEditForm() does not exist on SilverStripe\Control\Controller. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

704
            /** @scrutinizer ignore-call */ 
705
            $backForm = $toplevelController->getEditForm();
Loading history...
705
            $backForm->sessionMessage($message, 'good', ValidationResult::CAST_HTML);
706
        } else {
707
            $form->sessionMessage($message, 'good', ValidationResult::CAST_HTML);
708
        }
709
710
        //when an item is deleted, redirect to the parent controller
711
        $controller = $this->getToplevelController();
712
        $controller->getRequest()->addHeader('X-Pjax', 'Content'); // Force a content refresh
713
714
        return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section
715
    }
716
717
    /**
718
     * @param string $template
719
     * @return $this
720
     */
721
    public function setTemplate($template)
722
    {
723
        $this->template = $template;
724
        return $this;
725
    }
726
727
    /**
728
     * @return string
729
     */
730
    public function getTemplate()
731
    {
732
        return $this->template;
733
    }
734
735
    /**
736
     * Get list of templates to use
737
     *
738
     * @return array
739
     */
740
    public function getTemplates()
741
    {
742
        $templates = SSViewer::get_templates_by_class($this, '', __CLASS__);
743
        // Prefer any custom template
744
        if ($this->getTemplate()) {
745
            array_unshift($templates, $this->getTemplate());
746
        }
747
        return $templates;
748
    }
749
750
    /**
751
     * @return Controller
752
     */
753
    public function getController()
754
    {
755
        return $this->popupController;
756
    }
757
758
    /**
759
     * @return GridField
760
     */
761
    public function getGridField()
762
    {
763
        return $this->gridField;
764
    }
765
766
    /**
767
     * @return DataObject
768
     */
769
    public function getRecord()
770
    {
771
        return $this->record;
772
    }
773
774
    /**
775
     * CMS-specific functionality: Passes through navigation breadcrumbs
776
     * to the template, and includes the currently edited record (if any).
777
     * see {@link LeftAndMain->Breadcrumbs()} for details.
778
     *
779
     * @param boolean $unlinked
780
     * @return ArrayList
781
     */
782
    public function Breadcrumbs($unlinked = false)
783
    {
784
        if (!$this->popupController->hasMethod('Breadcrumbs')) {
785
            return null;
786
        }
787
788
        /** @var ArrayList $items */
789
        $items = $this->popupController->Breadcrumbs($unlinked);
790
791
        if (!$items) {
0 ignored issues
show
introduced by
$items is of type SilverStripe\ORM\ArrayList, thus it always evaluated to true.
Loading history...
792
            $items = new ArrayList();
793
        }
794
795
        if ($this->record && $this->record->ID) {
796
            $title = ($this->record->Title) ? $this->record->Title : "#{$this->record->ID}";
797
            $items->push(new ArrayData([
798
                'Title' => $title,
799
                'Link' => $this->Link()
800
            ]));
801
        } else {
802
            $items->push(new ArrayData([
803
                'Title' => _t('SilverStripe\\Forms\\GridField\\GridField.NewRecord', 'New {type}', ['type' => $this->record->i18n_singular_name()]),
804
                'Link' => false
805
            ]));
806
        }
807
808
        $this->extend('updateBreadcrumbs', $items);
809
        return $items;
810
    }
811
}
812