GridFieldDetailForm_ItemRequest::getController()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
     *
41
     * @var GridField
42
     */
43
    protected $gridField;
44
45
    /**
46
     *
47
     * @var GridFieldDetailForm
48
     */
49
    protected $component;
50
51
    /**
52
     * @var DataObject
53
     */
54
    protected $record;
55
56
    /**
57
     * This represents the current parent RequestHandler (which does not necessarily need to be a Controller).
58
     * It allows us to traverse the RequestHandler chain upwards to reach the Controller stack.
59
     *
60
     * @var RequestHandler
61
     */
62
    protected $popupController;
63
64
    /**
65
     *
66
     * @var string
67
     */
68
    protected $popupFormName;
69
70
    /**
71
     * @var String
72
     */
73
    protected $template = null;
74
75
    private static $url_handlers = [
76
        '$Action!' => '$Action',
77
        '' => 'edit',
78
    ];
79
80
    /**
81
     *
82
     * @param GridField $gridField
83
     * @param GridFieldDetailForm $component
84
     * @param DataObject $record
85
     * @param RequestHandler $requestHandler
86
     * @param string $popupFormName
87
     */
88
    public function __construct($gridField, $component, $record, $requestHandler, $popupFormName)
89
    {
90
        $this->gridField = $gridField;
91
        $this->component = $component;
92
        $this->record = $record;
93
        $this->popupController = $requestHandler;
94
        $this->popupFormName = $popupFormName;
95
        parent::__construct();
96
    }
97
98
    public function Link($action = null)
99
    {
100
        return Controller::join_links(
101
            $this->gridField->Link('item'),
102
            $this->record->ID ? $this->record->ID : 'new',
103
            $action
104
        );
105
    }
106
107
    /**
108
     * @param HTTPRequest $request
109
     * @return mixed
110
     */
111
    public function view($request)
112
    {
113
        if (!$this->record->canView()) {
114
            $this->httpError(403);
115
        }
116
117
        $controller = $this->getToplevelController();
118
119
        $form = $this->ItemEditForm();
120
        $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

120
        $form->/** @scrutinizer ignore-call */ 
121
               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...
121
122
        $data = new ArrayData(array(
123
            'Backlink'     => $controller->Link(),
124
            'ItemEditForm' => $form
125
        ));
126
        $return = $data->renderWith($this->getTemplates());
127
128
        if ($request->isAjax()) {
129
            return $return;
130
        } else {
131
            return $controller->customise(array('Content' => $return));
132
        }
133
    }
134
135
    /**
136
     * @param HTTPRequest $request
137
     * @return mixed
138
     */
139
    public function edit($request)
140
    {
141
        $controller = $this->getToplevelController();
142
        $form = $this->ItemEditForm();
143
144
        $return = $this->customise(array(
145
            '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

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

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

582
        $map = $list->/** @scrutinizer ignore-call */ limit($limit, $limitOffset)->column('ID');
Loading history...
583
        $index = array_search($this->record->ID, $map);
584
        return isset($map[$index+$offset]) ? $map[$index+$offset] : false;
585
    }
586
587
    /**
588
     * Gets the ID of the previous record in the list.
589
     *
590
     * @return int
591
     */
592
    public function getPreviousRecordID()
593
    {
594
        return $this->getAdjacentRecordID(-1);
595
    }
596
597
    /**
598
     * Gets the ID of the next record in the list.
599
     *
600
     * @return int
601
     */
602
    public function getNextRecordID()
603
    {
604
        return $this->getAdjacentRecordID(1);
605
    }
606
607
    /**
608
     * Response object for this request after a successful save
609
     *
610
     * @param bool $isNewRecord True if this record was just created
611
     * @return HTTPResponse|DBHTMLText
612
     */
613
    protected function redirectAfterSave($isNewRecord)
614
    {
615
        $controller = $this->getToplevelController();
616
        if ($isNewRecord) {
617
            return $controller->redirect($this->Link());
618
        } 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

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

668
        $list->/** @scrutinizer ignore-call */ 
669
               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...
669
670
        return $this->record;
671
    }
672
673
    /**
674
     * @param array $data
675
     * @param Form $form
676
     * @return HTTPResponse
677
     * @throws ValidationException
678
     */
679
    public function doDelete($data, $form)
680
    {
681
        $title = $this->record->Title;
682
        if (!$this->record->canDelete()) {
683
            throw new ValidationException(
684
                _t(
685
                    'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.DeletePermissionsFailure',
686
                    "No delete permissions"
687
                )
688
            );
689
        }
690
        $this->record->delete();
691
692
        $message = _t(
693
            'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Deleted',
694
            'Deleted {type} {name}',
695
            [
696
                'type' => $this->record->i18n_singular_name(),
697
                'name' => htmlspecialchars($title, ENT_QUOTES)
698
            ]
699
        );
700
701
        $toplevelController = $this->getToplevelController();
702
        if ($toplevelController && $toplevelController instanceof LeftAndMain) {
703
            $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

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