Skip to content

Instantly share code, notes, and snippets.

@hailwood
Created August 26, 2015 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hailwood/5d5d3dad6d061fd5d9de to your computer and use it in GitHub Desktop.
Save hailwood/5d5d3dad6d061fd5d9de to your computer and use it in GitHub Desktop.
<?php
class GridFieldCustomSiteTreeAddNewButton extends GridFieldAddNewButton implements GridField_ActionProvider {
/** @var SiteTree */
protected $parentPage;
public function __construct($targetFragment = 'before', SiteTree $parent) {
parent::__construct($targetFragment);
$this->parentPage = $parent;
}
public function getHTMLFragments($gridField) {
/** @var GridField $gridField */
$state = $gridField->State->GridFieldCustomSiteTreeAddNewButton;
if ($this->parentPage) {
$state->currentPageID = $this->parentPage->ID;
}
$pageTypes = HiddenField::create('PageType', 'Page Type', 'WinePage');
$state->pageType = 'WinePage';
$this->buttonName = 'Add New Wine';
$addAction = new GridField_FormAction($gridField, 'add', $this->buttonName, 'add', 'add');
$addAction->setAttribute('data-icon', 'add')->addExtraClass("no-ajax ss-ui-action-constructive dropdown-action");
$forTemplate = new ArrayData(array());
$forTemplate->Fields = new ArrayList();
$forTemplate->Fields->push($pageTypes);
$forTemplate->Fields->push($addAction);
return array($this->targetFragment => $forTemplate->renderWith("GridFieldSiteTreeAddNewButton"));
}
/**
* Provide actions to this component.
*
* @param GridField $gridField
*
* @return array
**/
public function getActions($gridField) {
return ["add"];
}
/**
* Handles the add action, but only acts as a wrapper for {@link CMSPageAddController::doAdd()}
*
* @param GridField $gridField
* @param string $actionName
* @param mixed $arguments
* @param array $data
**/
public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
if ($actionName == "add") {
$tmpData = json_decode($data[$gridField->getName()]['GridState'], true);
$tmpData = $tmpData['GridFieldCustomSiteTreeAddNewButton'];
$data = array(
"ParentID" => $tmpData['currentPageID'],
"PageType" => $tmpData['pageType']
);
$controller = Injector::inst()->create("CMSPageAddController");
$form = $controller->AddForm();
$form->loadDataFrom($data);
$controller->doAdd($data, $form);
$response = $controller->getResponseNegotiator()->getResponse();
// Get the current record
$record = SiteTree::get()->byId($controller->currentPageID());
if ($record) {
$response->redirect(Director::absoluteBaseURL() . $record->CMSEditLink(), 301);
}
return $response;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment