silverstripe-framework/src/Forms/GridField/GridFieldDetailForm_ItemRequest.php

763 lines
25 KiB
PHP
Raw Normal View History

<?php
namespace SilverStripe\Forms\GridField;
use SilverStripe\Admin\LeftAndMain;
use SilverStripe\Control\Controller;
2016-09-09 08:43:05 +02:00
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
API Refactor bootstrap, request handling See https://github.com/silverstripe/silverstripe-framework/pull/7037 and https://github.com/silverstripe/silverstripe-framework/issues/6681 Squashed commit of the following: commit 8f65e5653211240650eaa4fa65bb83b45aae6d58 Author: Ingo Schommer <me@chillu.com> Date: Thu Jun 22 22:25:50 2017 +1200 Fixed upgrade guide spelling commit 76f95944fa89b0b540704b8d744329f690f9698c Author: Damian Mooyman <damian@silverstripe.com> Date: Thu Jun 22 16:38:34 2017 +1200 BUG Fix non-test class manifest including sapphiretest / functionaltest commit 9379834cb4b2e5177a2600049feec05bf111c16b Author: Damian Mooyman <damian@silverstripe.com> Date: Thu Jun 22 15:50:47 2017 +1200 BUG Fix nesting bug in Kernel commit 188ce35d82599360c40f0f2de29579c56fb90761 Author: Damian Mooyman <damian@silverstripe.com> Date: Thu Jun 22 15:14:51 2017 +1200 BUG fix db bootstrapping issues commit 7ed4660e7a63915e8e974deeaba9807bc4d38b0d Author: Damian Mooyman <damian@silverstripe.com> Date: Thu Jun 22 14:49:07 2017 +1200 BUG Fix issue in DetailedErrorFormatter commit 738f50c497166f81ccbe3f40fbcff895ce71f82f Author: Damian Mooyman <damian@silverstripe.com> Date: Thu Jun 22 11:49:19 2017 +1200 Upgrading notes on mysite/_config.php commit 6279d28e5e455916f902a2f963c014d8899f7fc7 Author: Damian Mooyman <damian@silverstripe.com> Date: Thu Jun 22 11:43:28 2017 +1200 Update developer documentation commit 5c90d53a84ef0139c729396949a7857fae60436f Author: Damian Mooyman <damian@silverstripe.com> Date: Thu Jun 22 10:48:44 2017 +1200 Update installer to not use global databaseConfig commit f9b2ba4755371f08bd95f6908ac612fcbb7ca205 Author: Damian Mooyman <damian@silverstripe.com> Date: Wed Jun 21 21:04:39 2017 +1200 Fix behat issues commit 5b59a912b60282b4dad4ef10ed3b97c5d0a761ac Author: Damian Mooyman <damian@silverstripe.com> Date: Wed Jun 21 17:07:11 2017 +1200 Move HTTPApplication to SilverStripe\Control namespace commit e2c4a18f637bdd3d276619554de60ee8b4d95ced Author: Damian Mooyman <damian@silverstripe.com> Date: Wed Jun 21 16:29:03 2017 +1200 More documentation Fix up remaining tests Refactor temp DB into TempDatabase class so it’s available outside of unit tests. commit 5d235e64f341d6251bfe9f4833f15cc8593c5034 Author: Damian Mooyman <damian@silverstripe.com> Date: Wed Jun 21 12:13:15 2017 +1200 API HTTPRequestBuilder::createFromEnvironment() now cleans up live globals BUG Fix issue with SSViewer Fix Security / View tests commit d88d4ed4e48291cb65407f222f190064b1f1deeb Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 20 16:39:43 2017 +1200 API Refactor AppKernel into CoreKernel commit f7946aec3391139ae1b4029c353c327a36552b36 Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 20 16:00:40 2017 +1200 Docs and minor cleanup commit 12bd31f9366327650b5c0c0f96cd0327d44faf0a Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 20 15:34:34 2017 +1200 API Remove OutputMiddleware API Move environment / global / ini management into Environment class API Move getTempFolder into TempFolder class API Implement HTTPRequestBuilder / CLIRequestBuilder BUG Restore SS_ALLOWED_HOSTS check in original location API CoreKernel now requires $basePath to be passed in API Refactor installer.php to use application to bootstrap API move memstring conversion globals to Convert BUG Fix error in CoreKernel nesting not un-nesting itself properly. commit bba979114624247cf463cf2a8c9e4be9a7c3a772 Author: Damian Mooyman <damian@silverstripe.com> Date: Mon Jun 19 18:07:53 2017 +1200 API Create HTTPMiddleware and standardise middleware for request handling commit 2a10c2397bdc53001013f607b5d38087ce6c0730 Author: Damian Mooyman <damian@silverstripe.com> Date: Mon Jun 19 17:42:42 2017 +1200 Fixed ORM tests commit d75a8d1d93398af4bd0432df9e4bc6295c15a3fe Author: Damian Mooyman <damian@silverstripe.com> Date: Mon Jun 19 17:15:07 2017 +1200 FIx i18n tests commit 06364af3c379c931889c4cc34dd920fee3db204a Author: Damian Mooyman <damian@silverstripe.com> Date: Mon Jun 19 16:59:34 2017 +1200 Fix controller namespace Move states to sub namespace commit 2a278e2953d2dbb19f78d91c919048e1fc935436 Author: Damian Mooyman <damian@silverstripe.com> Date: Mon Jun 19 12:49:45 2017 +1200 Fix forms namespace commit b65c21241bee019730027071d815dbf7571197a4 Author: Damian Mooyman <damian@silverstripe.com> Date: Thu Jun 15 18:56:48 2017 +1200 Update API usages commit d1d4375c95a264a6b63cbaefc2c1d12f808bfd82 Author: Damian Mooyman <damian@silverstripe.com> Date: Thu Jun 15 18:41:44 2017 +1200 API Refactor $flush into HTPPApplication API Enforce health check in Controller::pushCurrent() API Better global backup / restore Updated Director::test() to use new API commit b220534f06732db4fa940d8724c2a85c0ba2495a Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 13 22:05:57 2017 +1200 Move app nesting to a test state helper commit 603704165c08d0c1c81fd5e6bb9506326eeee17b Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 13 21:46:04 2017 +1200 Restore kernel stack to fix multi-level nesting commit 2f6336a15bf79dc8c2edd44cec1931da2dd51c28 Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 13 17:23:21 2017 +1200 API Implement kernel nesting commit fc7188da7d6ad6785354bab61f08700454c81d91 Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 13 15:43:13 2017 +1200 Fix core tests commit a0ae7235148fffd71f2f02d1fe7fe45bf3aa39eb Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 13 15:23:52 2017 +1200 Fix manifest tests commit ca033952513633e182040d3d13e1caa9000ca184 Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 13 15:00:00 2017 +1200 API Move extension management into test state commit c66d4339777663a8a04661fea32a0cf35b95d20f Author: Damian Mooyman <damian@silverstripe.com> Date: Tue Jun 13 14:10:59 2017 +1200 API Refactor SapphireTest state management into SapphireTestState API Remove Injector::unregisterAllObjects() API Remove FakeController commit f26ae75c6ecaafa0dec1093264e0187191e6764d Author: Damian Mooyman <damian@silverstripe.com> Date: Mon Jun 12 18:04:34 2017 +1200 Implement basic CLI application object commit 001d5596621404892de0a5413392379eff990641 Author: Damian Mooyman <damian@silverstripe.com> Date: Mon Jun 12 17:39:38 2017 +1200 Remove references to SapphireTest::is_running_test() Upgrade various code commit de079c041dacd96bc4f4b66421fa2b2cc4c320f8 Author: Damian Mooyman <damian@silverstripe.com> Date: Wed Jun 7 18:07:33 2017 +1200 API Implement APP object API Refactor of Session
2017-06-22 12:50:45 +02:00
use SilverStripe\Control\RequestHandler;
use SilverStripe\Core\Config\Config;
use SilverStripe\Forms\CompositeField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\ORM\HasManyList;
use SilverStripe\ORM\ManyManyList;
use SilverStripe\ORM\SS_List;
use SilverStripe\ORM\ValidationException;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\View\ArrayData;
use SilverStripe\View\SSViewer;
class GridFieldDetailForm_ItemRequest extends RequestHandler
{
private static $allowed_actions = array(
'edit',
'view',
'ItemEditForm'
);
/**
*
* @var GridField
*/
protected $gridField;
/**
*
* @var GridFieldDetailForm
*/
protected $component;
/**
* @var DataObject
*/
protected $record;
/**
* This represents the current parent RequestHandler (which does not necessarily need to be a Controller).
* It allows us to traverse the RequestHandler chain upwards to reach the Controller stack.
*
* @var RequestHandler
*/
protected $popupController;
/**
*
* @var string
*/
protected $popupFormName;
/**
* @var String
*/
protected $template = null;
private static $url_handlers = array(
'$Action!' => '$Action',
'' => 'edit',
);
/**
*
* @param GridField $gridField
* @param GridFieldDetailForm $component
* @param DataObject $record
* @param RequestHandler $requestHandler
* @param string $popupFormName
*/
public function __construct($gridField, $component, $record, $requestHandler, $popupFormName)
{
$this->gridField = $gridField;
$this->component = $component;
$this->record = $record;
$this->popupController = $requestHandler;
$this->popupFormName = $popupFormName;
parent::__construct();
}
public function Link($action = null)
{
2016-11-29 00:31:16 +01:00
return Controller::join_links(
$this->gridField->Link('item'),
$this->record->ID ? $this->record->ID : 'new',
$action
);
}
/**
* @param HTTPRequest $request
* @return mixed
*/
public function view($request)
{
if (!$this->record->canView()) {
$this->httpError(403);
}
$controller = $this->getToplevelController();
$form = $this->ItemEditForm();
$form->makeReadonly();
$data = new ArrayData(array(
'Backlink' => $controller->Link(),
'ItemEditForm' => $form
));
$return = $data->renderWith($this->getTemplates());
if ($request->isAjax()) {
return $return;
} else {
return $controller->customise(array('Content' => $return));
}
}
/**
* @param HTTPRequest $request
* @return mixed
*/
public function edit($request)
{
$controller = $this->getToplevelController();
$form = $this->ItemEditForm();
$return = $this->customise(array(
'Backlink' => $controller->hasMethod('Backlink') ? $controller->Backlink() : $controller->Link(),
'ItemEditForm' => $form,
))->renderWith($this->getTemplates());
if ($request->isAjax()) {
return $return;
} else {
// If not requested by ajax, we need to render it within the controller context+template
return $controller->customise(array(
// TODO CMS coupling
'Content' => $return,
));
}
}
/**
* Builds an item edit form. The arguments to getCMSFields() are the popupController and
* popupFormName, however this is an experimental API and may change.
*
* @todo In the future, we will probably need to come up with a tigher object representing a partially
* complete controller with gaps for extra functionality. This, for example, would be a better way
* of letting Security/login put its log-in form inside a UI specified elsewhere.
*
* @return Form|HTTPResponse
*/
public function ItemEditForm()
{
$list = $this->gridField->getList();
if (empty($this->record)) {
$controller = $this->getToplevelController();
$url = $controller->getRequest()->getURL();
$noActionURL = $controller->removeAction($url);
$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) {
$controller = $this->getToplevelController();
// TODO More friendly error
return $controller->httpError(403);
}
// Build actions
$actions = $this->getFormActions();
// 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->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);
}
}
$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);
}
} elseif (!$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(array('ManyMany' => $extraData));
}
// TODO Coupling with CMS
$toplevelController = $this->getToplevelController();
if ($toplevelController && $toplevelController instanceof LeftAndMain) {
// Always show with base template (full width, no other panels),
// regardless of overloaded CMS controller templates.
// TODO Allow customization, e.g. to display an edit form alongside a search form from the CMS controller
$form->setTemplate([
'type' => 'Includes',
'SilverStripe\\Admin\\LeftAndMain_EditForm',
]);
$form->addExtraClass('cms-content cms-edit-form center fill-height flexbox-area-grow');
$form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
if ($form->Fields()->hasTabSet()) {
$form->Fields()->findOrMakeTab('Root')->setTemplate('SilverStripe\\Forms\\CMSTabSet');
$form->addExtraClass('cms-tabset');
}
$form->Backlink = $this->getBackLink();
}
$cb = $this->component->getItemEditFormCallback();
if ($cb) {
$cb($form, $this);
}
$this->extend("updateItemEditForm", $form);
return $form;
}
/**
* @return CompositeField Returns the right aligned toolbar group field along with its FormAction's
*/
protected function getRightGroupField()
{
$rightGroup = CompositeField::create()->setName('RightGroup');
$rightGroup->addExtraClass('ml-auto');
$rightGroup->setFieldHolderTemplate(get_class($rightGroup) . '_holder_buttongroup');
$previousAndNextGroup = CompositeField::create()->setName('PreviousAndNextGroup');
$previousAndNextGroup->addExtraClass('circular-group mr-2');
$previousAndNextGroup->setFieldHolderTemplate(get_class($previousAndNextGroup) . '_holder_buttongroup');
/** @var GridFieldDetailForm $component */
$component = $this->gridField->getConfig()->getComponentByType(GridFieldDetailForm::class);
$gridState = $this->getRequest()->requestVar('gridState');
if ($component && $component->getShowPagination()) {
$previousAndNextGroup->push(FormAction::create('doPrevious')
->setUseButtonTag(true)
->setAttribute('data-grid-state', $gridState)
->setDisabled(!$this->getPreviousRecordID())
->addExtraClass('btn btn-secondary font-icon-left-open action--previous discard-confirmation'));
$previousAndNextGroup->push(FormAction::create('doNext')
->setUseButtonTag(true)
->setAttribute('data-grid-state', $gridState)
->setDisabled(!$this->getNextRecordID())
->addExtraClass('btn btn-secondary font-icon-right-open action--next discard-confirmation'));
}
$rightGroup->push($previousAndNextGroup);
if ($component && $component->getShowAdd()) {
$rightGroup->push(FormAction::create('doNew')
->setUseButtonTag(true)
->setAttribute('data-grid-state', $this->getRequest()->getVar('gridState'))
->addExtraClass('btn btn-primary font-icon-plus-thin circular action--new discard-confirmation'));
}
return $rightGroup;
}
/**
* Build the set of form field actions for this DataObject
*
* @return FieldList
*/
protected function getFormActions()
{
$actions = new FieldList();
if ($this->record->ID !== 0) { // existing record
if ($this->record->canEdit()) {
2017-04-20 03:15:24 +02:00
$actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Save', 'Save'))
->setUseButtonTag(true)
->addExtraClass('btn-primary font-icon-save'));
}
if ($this->record->canDelete()) {
2017-04-20 03:15:24 +02:00
$actions->push(FormAction::create('doDelete', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete', 'Delete'))
->setUseButtonTag(true)
->addExtraClass('btn-outline-danger btn-hide-outline font-icon-trash-bin action--delete'));
}
$gridState = $this->getRequest()->requestVar('gridState');
$this->gridField->getState(false)->setValue($gridState);
$actions->push(HiddenField::create('gridState', null, $gridState));
$actions->push($this->getRightGroupField());
} else { // adding new record
//Change the Save label to 'Create'
2017-04-20 03:15:24 +02:00
$actions->push(FormAction::create('doSave', _t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Create', 'Create'))
->setUseButtonTag(true)
->addExtraClass('btn-primary font-icon-plus-thin'));
// Add a Cancel link which is a button-like link and link back to one level up.
$crumbs = $this->Breadcrumbs();
if ($crumbs && $crumbs->count() >= 2) {
$oneLevelUp = $crumbs->offsetGet($crumbs->count() - 2);
$text = sprintf(
"<a class=\"%s\" href=\"%s\">%s</a>",
"crumb btn btn-secondary cms-panel-link", // CSS classes
$oneLevelUp->Link, // url
2017-04-20 03:15:24 +02:00
_t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.CancelBtn', 'Cancel') // label
);
$actions->push(new LiteralField('cancelbutton', $text));
}
}
$this->extend('updateFormActions', $actions);
return $actions;
}
/**
* Traverse the nested RequestHandlers until we reach something that's not GridFieldDetailForm_ItemRequest.
* This allows us to access the Controller responsible for invoking the top-level GridField.
* This should be equivalent to getting the controller off the top of the controller stack via Controller::curr(),
* but allows us to avoid accessing the global state.
*
* GridFieldDetailForm_ItemRequests are RequestHandlers, and as such they are not part of the controller stack.
*
* @return Controller
*/
protected function getToplevelController()
{
$c = $this->popupController;
while ($c && $c instanceof GridFieldDetailForm_ItemRequest) {
$c = $c->getController();
}
return $c;
}
protected function getBackLink()
{
// TODO Coupling with CMS
$backlink = '';
$toplevelController = $this->getToplevelController();
if ($toplevelController && $toplevelController instanceof LeftAndMain) {
if ($toplevelController->hasMethod('Backlink')) {
$backlink = $toplevelController->Backlink();
} elseif ($this->popupController->hasMethod('Breadcrumbs')) {
$parents = $this->popupController->Breadcrumbs(false)->items;
$backlink = array_pop($parents)->Link;
}
}
if (!$backlink) {
$backlink = $toplevelController->Link();
}
return $backlink;
}
/**
* Get the list of extra data from the $record as saved into it by
* {@see Form::saveInto()}
*
* Handles detection of falsey values explicitly saved into the
* DataObject by formfields
*
* @param DataObject $record
* @param SS_List $list
* @return array List of data to write to the relation
*/
protected function getExtraSavedData($record, $list)
{
// Skip extra data if not ManyManyList
if (!($list instanceof ManyManyList)) {
return null;
}
$data = array();
foreach ($list->getExtraFields() as $field => $dbSpec) {
$savedField = "ManyMany[{$field}]";
if ($record->hasField($savedField)) {
$data[$field] = $record->getField($savedField);
}
}
return $data;
}
public function doSave($data, $form)
{
$isNewRecord = $this->record->ID == 0;
// Check permission
if (!$this->record->canEdit()) {
return $this->httpError(403);
}
// Save from form data
$this->saveFormIntoRecord($data, $form);
$link = '<a href="' . $this->Link('edit') . '">"'
. htmlspecialchars($this->record->Title, ENT_QUOTES)
. '"</a>';
$message = _t(
2017-04-20 03:15:24 +02:00
'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Saved',
'Saved {name} {link}',
array(
'name' => $this->record->i18n_singular_name(),
'link' => $link
)
);
$form->sessionMessage($message, 'good', ValidationResult::CAST_HTML);
// Redirect after save
return $this->redirectAfterSave($isNewRecord);
}
/**
* Goes to the previous record
* @param array $data The form data
* @param Form $form The Form object
* @return HTTPResponse
*/
public function doPrevious($data, $form)
{
$this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content');
$link = $this->getEditLink($this->getPreviousRecordID());
return $this->redirect($link);
}
/**
* Goes to the next record
* @param array $data The form data
* @param Form $form The Form object
* @return HTTPResponse
*/
public function doNext($data, $form)
{
$this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content');
$link = $this->getEditLink($this->getNextRecordID());
return $this->redirect($link);
}
/**
* Creates a new record. If you're already creating a new record,
* this forces the URL to change.
*
* @param array $data The form data
* @param Form $form The Form object
* @return HTTPResponse
*/
public function doNew($data, $form)
{
return $this->redirect(Controller::join_links($this->gridField->Link('item'), 'new'));
}
/**
* Gets the edit link for a record
*
* @param int $id The ID of the record in the GridField
* @return string
*/
public function getEditLink($id)
{
return Controller::join_links(
$this->gridField->Link(),
'item',
$id,
'?gridState=' . urlencode($this->gridField->getState(false)->Value())
);
}
/**
* @param int $offset The offset from the current record
* @return int|bool
*/
private function getAdjacentRecordID($offset)
{
$gridField = $this->getGridField();
$gridStateStr = $this->getRequest()->requestVar('gridState');
$state = $gridField->getState(false);
$state->setValue($gridStateStr);
$data = $state->getData();
$paginator = $data->getData('GridFieldPaginator');
if (!$paginator) {
return false;
}
$currentPage = $paginator->getData('currentPage');
$itemsPerPage = $paginator->getData('itemsPerPage');
$limit = $itemsPerPage + 2;
$limitOffset = max(0, $itemsPerPage * ($currentPage-1) -1);
$map = $gridField->getManipulatedList()->limit($limit, $limitOffset)->column('ID');
$index = array_search($this->record->ID, $map);
return isset($map[$index+$offset]) ? $map[$index+$offset] : false;
}
/**
* Gets the ID of the previous record in the list.
*
* @return int
*/
public function getPreviousRecordID()
{
return $this->getAdjacentRecordID(-1);
}
/**
* Gets the ID of the next record in the list.
*
* @return int
*/
public function getNextRecordID()
{
return $this->getAdjacentRecordID(1);
}
/**
* Response object for this request after a successful save
*
* @param bool $isNewRecord True if this record was just created
* @return HTTPResponse|DBHTMLText
*/
protected function redirectAfterSave($isNewRecord)
{
$controller = $this->getToplevelController();
if ($isNewRecord) {
return $controller->redirect($this->Link());
} elseif ($this->gridField->getList()->byID($this->record->ID)) {
// Return new view, as we can't do a "virtual redirect" via the CMS Ajax
// to the same URL (it assumes that its content is already current, and doesn't reload)
return $this->edit($controller->getRequest());
} 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
$url = $controller->getRequest()->getURL();
$noActionURL = $controller->removeAction($url);
$controller->getRequest()->addHeader('X-Pjax', 'Content');
return $controller->redirect($noActionURL, 302);
}
}
public function httpError($errorCode, $errorMessage = null)
{
$controller = $this->getToplevelController();
return $controller->httpError($errorCode, $errorMessage);
}
/**
* Loads the given form data into the underlying dataobject and relation
*
* @param array $data
* @param Form $form
* @throws ValidationException On error
* @return DataObject Saved record
*/
protected function saveFormIntoRecord($data, $form)
{
$list = $this->gridField->getList();
// Check object matches the correct classname
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);
}
// Save form and any extra saved data into this dataobject
$form->saveInto($this->record);
$this->record->write();
$this->extend('onAfterSave', $this->record);
$extraData = $this->getExtraSavedData($this->record, $list);
$list->add($this->record, $extraData);
return $this->record;
}
/**
* @param array $data
* @param Form $form
* @return HTTPResponse
* @throws ValidationException
*/
public function doDelete($data, $form)
{
$title = $this->record->Title;
if (!$this->record->canDelete()) {
throw new ValidationException(
2017-04-20 03:15:24 +02:00
_t('SilverStripe\\Forms\\GridField\\GridFieldDetailForm.DeletePermissionsFailure', "No delete permissions")
);
}
$this->record->delete();
$message = _t(
'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Deleted',
'Deleted {type} {name}',
[
'type' => $this->record->i18n_singular_name(),
'name' => htmlspecialchars($title, ENT_QUOTES)
]
);
$toplevelController = $this->getToplevelController();
if ($toplevelController && $toplevelController instanceof LeftAndMain) {
$backForm = $toplevelController->getEditForm();
$backForm->sessionMessage($message, 'good', ValidationResult::CAST_HTML);
} else {
$form->sessionMessage($message, 'good', ValidationResult::CAST_HTML);
}
//when an item is deleted, redirect to the parent controller
$controller = $this->getToplevelController();
$controller->getRequest()->addHeader('X-Pjax', 'Content'); // Force a content refresh
return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section
}
/**
* @param string $template
* @return $this
*/
public function setTemplate($template)
{
$this->template = $template;
return $this;
}
/**
* @return string
*/
public function getTemplate()
{
return $this->template;
}
/**
* Get list of templates to use
*
* @return array
*/
public function getTemplates()
{
$templates = SSViewer::get_templates_by_class($this, '', __CLASS__);
// Prefer any custom template
if ($this->getTemplate()) {
array_unshift($templates, $this->getTemplate());
}
return $templates;
}
/**
* @return Controller
*/
public function getController()
{
return $this->popupController;
}
/**
* @return GridField
*/
public function getGridField()
{
return $this->gridField;
}
/**
* @return DataObject
*/
public function getRecord()
{
return $this->record;
}
/**
* CMS-specific functionality: Passes through navigation breadcrumbs
* to the template, and includes the currently edited record (if any).
* see {@link LeftAndMain->Breadcrumbs()} for details.
*
* @param boolean $unlinked
* @return ArrayList
*/
public function Breadcrumbs($unlinked = false)
{
if (!$this->popupController->hasMethod('Breadcrumbs')) {
return null;
}
/** @var ArrayList $items */
$items = $this->popupController->Breadcrumbs($unlinked);
if ($this->record && $this->record->ID) {
$title = ($this->record->Title) ? $this->record->Title : "#{$this->record->ID}";
$items->push(new ArrayData(array(
'Title' => $title,
'Link' => $this->Link()
)));
} else {
$items->push(new ArrayData(array(
'Title' => _t('SilverStripe\\Forms\\GridField\\GridField.NewRecord', 'New {type}', ['type' => $this->record->i18n_singular_name()]),
'Link' => false
)));
}
$this->extend('updateBreadcrumbs', $items);
return $items;
}
}