-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathGridFieldDetailForm_ItemRequest.php
324 lines (272 loc) · 12.2 KB
/
GridFieldDetailForm_ItemRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
<?php
namespace WebbuildersGroup\FrontEndGridField\Forms\GridField;
use SilverStripe\Admin\LeftAndMain;
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest as SS_GridFieldDetailForm_ItemRequest;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\ORM\HasManyList;
use SilverStripe\ORM\ManyManyList;
use SilverStripe\ORM\ValidationException;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\View\Requirements;
class GridFieldDetailForm_ItemRequest extends SS_GridFieldDetailForm_ItemRequest
{
private static $allowed_actions = [
'view',
'edit',
'ItemEditForm',
];
/**
* Builds an item edit form. The arguments to getFrontEndFields() are the popupController and popupFormName, however this is an experimental API and may change.
* @return Form
*/
public function ItemEditForm()
{
$list = $this->gridField->getList();
if (empty($this->record)) {
$controller = $this->getToplevelController();
$noActionURL = $controller->removeAction($controller->getRequest()->getURL(true));
$controller->getResponse()->removeHeader('Location'); //clear the existing redirect
return $controller->redirect($noActionURL, 302);
}
$canView = $this->record->canView();
$canEdit = $this->record->canEdit();
$canDelete = $this->record->canDelete();
$canCreate = $this->record->canCreate();
if (!$canView) {
return $this->getToplevelController()->httpError(403);
}
$actions = new FieldList();
if ($this->record->ID !== 0) {
if ($canEdit) {
$actions->push(
FormAction::create('doSave', _t('GridFieldDetailForm.Save', 'Save'))
->setUseButtonTag(true)
->addExtraClass('btn-primary font-icon-save')
->setAttribute('data-icon', 'accept')
);
}
if ($canDelete) {
$actions->push(
FormAction::create('doDelete', _t('GridFieldDetailForm.Delete', 'Delete'))
->setUseButtonTag(true)
->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action-delete')
);
}
} else { // adding new record
//Change the Save label to 'Create'
$actions->push(
FormAction::create('doSave', _t('GridFieldDetailForm.Create', 'Create'))
->setUseButtonTag(true)
->addExtraClass('btn-primary font-icon-plus-thin')
->setAttribute('data-icon', 'add')
);
// Add a Cancel link which is a button-like link and link back to one level up.
$curmbs = $this->Breadcrumbs();
if ($curmbs && $curmbs->count() >= 2) {
$one_level_up = $curmbs->offsetGet($curmbs->count() - 2);
$text = sprintf(
"<a class=\"%s\" href=\"%s\">%s</a>",
"crumb ss-ui-button btn-outline-danger btn-hide-outline font-icon-trash-bin cms-panel-link ui-corner-all", // CSS classes
$one_level_up->Link, // url
_t('GridFieldDetailForm.CancelBtn', 'Cancel') // label
);
$actions->push(new LiteralField('cancelbutton', $text));
}
}
// If we are creating a new record in a has-many list, then
// pre-populate the record's foreign key.
if ($list instanceof HasManyList && !$this->record->isInDB()) {
$key = $list->getForeignKey();
$id = $list->getForeignID();
$this->record->$key = $id;
}
$fields = $this->component->getFields();
if (!$fields) {
$fields = ($this->record->hasMethod('getFrontEndFields') ? $this->record->getFrontEndFields() : $this->record->getCMSFields());
}
// If we are creating a new record in a has-many list, then
// Disable the form field as it has no effect.
if ($list instanceof HasManyList) {
$key = $list->getForeignKey();
if ($field = $fields->dataFieldByName($key)) {
$fields->makeFieldReadonly($field);
}
}
// this pushes the current page ID in as a hidden field
// this means the request will have the current page ID in it
// rather than relying on session which can have been rewritten
// by the user having another tab open
// see LeftAndMain::currentPageID
if ($this->controller->hasMethod('currentPageID') && $this->controller->currentPageID()) {
$fields->push(new HiddenField('CMSMainCurrentPageID', null, $this->controller->currentPageID()));
}
// Caution: API violation. Form expects a Controller, but we are giving it a RequestHandler instead.
// Thanks to this however, we are able to nest GridFields, and also access the initial Controller by
// dereferencing GridFieldDetailForm_ItemRequest->getController() multiple times. See getToplevelController
// below.
$form = new Form(
$this,
'ItemEditForm',
$fields,
$actions,
$this->component->getValidator()
);
$form->loadDataFrom($this->record, ($this->record->ID == 0 ? Form::MERGE_IGNORE_FALSEISH : Form::MERGE_DEFAULT));
if ($this->record->ID && !$canEdit) {
// Restrict editing of existing records
$form->makeReadonly();
// Hack to re-enable delete button if user can delete
if ($canDelete) {
$form->Actions()->fieldByName('action_doDelete')->setReadonly(false);
}
} else if (!$this->record->ID && !$canCreate) {
// Restrict creation of new records
$form->makeReadonly();
}
// Load many_many extraData for record.
// Fields with the correct 'ManyMany' namespace need to be added manually through getCMSFields().
if ($list instanceof ManyManyList) {
$extraData = $list->getExtraData('', $this->record->ID);
$form->loadDataFrom(['ManyMany' => $extraData]);
}
$cb = $this->component->getItemEditFormCallback();
if ($cb) {
$cb($form, $this);
}
$this->extend("updateItemEditForm", $form);
return $form;
}
/**
* Renders the view form
* @param {SS_HTTPRequest} $request Request data
* @return {string} Rendered view form
*/
public function view($request)
{
if (!$this->record->canView()) {
$this->httpError(403);
}
$controller = $this->getToplevelController();
$form = $this->ItemEditForm($this->gridField, $request);
if (!is_a($form, Form::class)) {
return $form;
}
$form->makeReadonly();
return $controller->customise([
'Title' => ($this->record && $this->record->exists() ? $this->record->Title : sprintf(_t('GridField.NewRecord', 'New %s'), singleton($this->gridField->getModelClass())->i18n_singular_name())),
'ItemEditForm' => $form,
])->renderWith($this->template);
}
/**
* Renders the edit form
* @param {SS_HTTPRequest} $request Request data
* @return {string} Rendered edit form
*/
public function edit($request)
{
$controller = $this->getToplevelController();
$form = $this->ItemEditForm($this->gridField, $request);
if (!is_a($form, Form::class)) {
return $form;
}
return $controller->customise([
'Title' => ($this->record && $this->record->exists() ? $this->record->Title : sprintf(_t('GridField.NewRecord', 'New %s'), singleton($this->gridField->getModelClass())->i18n_singular_name())),
'ItemEditForm' => $form,
])->renderWith($this->template);
}
/**
* Disabled, the front end does not use breadcrumbs to remember the paths
*/
public function Breadcrumbs($unlinked = false)
{
return;
}
public function doSave($data, $form)
{
$new_record = $this->record->ID == 0;
$controller = $this->getToplevelController();
$list = $this->gridField->getList();
if (!$this->record->canEdit()) {
return $controller->httpError(403);
}
if (isset($data['ClassName']) && $data['ClassName'] != $this->record->ClassName) {
$newClassName = $data['ClassName'];
// The records originally saved attribute was overwritten by $form->saveInto($record) before.
// This is necessary for newClassInstance() to work as expected, and trigger change detection
// on the ClassName attribute
$this->record->setClassName($this->record->ClassName);
// Replace $record with a new instance
$this->record = $this->record->newClassInstance($newClassName);
}
try {
$form->saveInto($this->record);
$this->record->write();
$extraData = $this->getExtraSavedData($this->record, $list);
$list->add($this->record, $extraData);
} catch (ValidationException $e) {
$form->setSessionValidationResult($e->getResult());
$controller->getRequest()->getSession()->set("FormInfo.{$form->FormName()}.data", $form->getData());
return $controller->redirectBack();
}
// TODO Save this item into the given relationship
$link = '<a href="' . $this->Link('edit') . '">"' . htmlspecialchars($this->record->Title, ENT_QUOTES) . '"</a>';
$message = _t(
'GridFieldDetailForm.Saved',
'Saved {name} {link}',
[
'name' => $this->record->i18n_singular_name(),
'link' => $link,
]
);
$form->sessionMessage($message, ValidationResult::TYPE_GOOD, ValidationResult::CAST_HTML);
if ($new_record) {
return $controller->redirect($this->Link());
} else if ($this->gridField->getList()->byId($this->record->ID)) {
return $controller->redirectBack();
} else {
// Changes to the record properties might've excluded the record from
// a filtered list, so return back to the main view if it can't be found
$noActionURL = $controller->removeAction($data['url']);
$controller->getRequest()->addHeader('X-Pjax', 'Content');
return $controller->redirect($noActionURL, 302);
}
}
public function doDelete($data, $form)
{
$title = $this->record->Title;
try {
if (!$this->record->canDelete()) {
throw new ValidationException(_t('GridFieldDetailForm.DeletePermissionsFailure', "No delete permissions"), 0);
}
$this->record->delete();
} catch (ValidationException $e) {
$form->sessionMessage($e->getResult()->message(), ValidationResult::TYPE_ERROR);
return Controller::curr()->redirectBack();
}
$message = sprintf(_t('GridFieldDetailForm.Deleted', 'Deleted %s %s'), $this->record->i18n_singular_name(), htmlspecialchars($title, ENT_QUOTES));
$toplevelController = $this->getToplevelController();
if ($toplevelController && $toplevelController instanceof LeftAndMain) {
$backForm = $toplevelController->getEditForm();
$backForm->sessionMessage($message, ValidationResult::TYPE_GOOD);
} else {
$form->sessionMessage($message, ValidationResult::TYPE_GOOD);
}
//Remove all requirements
Requirements::clear();
return $this->customise(['GridFieldID' => $this->gridField->ID()])->renderWith(GridField::class . '_deleted');
}
/**
* Wrapper for redirectBack()
* @see Controller::redirectBack()
*/
public function redirectBack(): HTTPResponse
{
return Controller::curr()->redirectBack();
}
}