PSR-2 code style guidelines

This commit is contained in:
Robbie Averill 2016-12-21 15:34:58 +13:00
parent 4ee047b591
commit 2acf6dee47
14 changed files with 1661 additions and 1550 deletions

View File

@ -11,7 +11,8 @@ use SilverStripe\View\ArrayData;
* A modal search dialog which uses search context to search for and add * A modal search dialog which uses search context to search for and add
* existing records to a grid field. * existing records to a grid field.
*/ */
class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridField_URLHandler { class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridField_URLHandler
{
private static $allowed_actions = array( private static $allowed_actions = array(
'handleSearch' 'handleSearch'
@ -24,7 +25,8 @@ class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridFi
/** /**
* @param string $fragment * @param string $fragment
*/ */
public function __construct($fragment = 'buttons-before-left') { public function __construct($fragment = 'buttons-before-left')
{
$this->fragment = $fragment; $this->fragment = $fragment;
$this->title = _t('GridFieldExtensions.ADDEXISTING', 'Add Existing'); $this->title = _t('GridFieldExtensions.ADDEXISTING', 'Add Existing');
} }
@ -32,7 +34,8 @@ class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridFi
/** /**
* @return string * @return string
*/ */
public function getTitle() { public function getTitle()
{
return $this->title; return $this->title;
} }
@ -40,7 +43,8 @@ class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridFi
* @param string $title * @param string $title
* @return GridFieldAddExistingSearchButton $this * @return GridFieldAddExistingSearchButton $this
*/ */
public function setTitle($title) { public function setTitle($title)
{
$this->title = $title; $this->title = $title;
return $this; return $this;
} }
@ -48,7 +52,8 @@ class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridFi
/** /**
* @return string * @return string
*/ */
public function getFragment() { public function getFragment()
{
return $this->fragment; return $this->fragment;
} }
@ -56,7 +61,8 @@ class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridFi
* @param string $fragment * @param string $fragment
* @return GridFieldAddExistingSearchButton $this * @return GridFieldAddExistingSearchButton $this
*/ */
public function setFragment($fragment) { public function setFragment($fragment)
{
$this->fragment = $fragment; $this->fragment = $fragment;
return $this; return $this;
} }
@ -67,7 +73,8 @@ class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridFi
* @param SS_List $list * @param SS_List $list
* @return GridFieldAddExistingSearchButton $this * @return GridFieldAddExistingSearchButton $this
*/ */
public function setSearchList(SS_List $list) { public function setSearchList(SS_List $list)
{
$this->searchList = $list; $this->searchList = $list;
return $this; return $this;
} }
@ -75,11 +82,13 @@ class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridFi
/** /**
* @return SS_List|null * @return SS_List|null
*/ */
public function getSearchList() { public function getSearchList()
{
return $this->searchList; return $this->searchList;
} }
public function getHTMLFragments($grid) { public function getHTMLFragments($grid)
{
GridFieldExtensions::include_requirements(); GridFieldExtensions::include_requirements();
$data = new ArrayData(array( $data = new ArrayData(array(
@ -92,14 +101,15 @@ class GridFieldAddExistingSearchButton implements GridField_HTMLProvider, GridFi
); );
} }
public function getURLHandlers($grid) { public function getURLHandlers($grid)
{
return array( return array(
'add-existing-search' => 'handleSearch' 'add-existing-search' => 'handleSearch'
); );
} }
public function handleSearch($grid, $request) { public function handleSearch($grid, $request)
{
return new GridFieldAddExistingSearchHandler($grid, $this); return new GridFieldAddExistingSearchHandler($grid, $this);
} }
} }

View File

@ -14,7 +14,8 @@ use SilverStripe\ORM\PaginatedList;
* Used by {@link GridFieldAddExistingSearchButton} to provide the searching * Used by {@link GridFieldAddExistingSearchButton} to provide the searching
* functionality. * functionality.
*/ */
class GridFieldAddExistingSearchHandler extends RequestHandler { class GridFieldAddExistingSearchHandler extends RequestHandler
{
private static $allowed_actions = array( private static $allowed_actions = array(
'index', 'index',
@ -37,7 +38,8 @@ class GridFieldAddExistingSearchHandler extends RequestHandler {
*/ */
protected $context; protected $context;
public function __construct($grid, $button) { public function __construct($grid, $button)
{
$this->grid = $grid; $this->grid = $grid;
$this->button = $button; $this->button = $button;
$this->context = singleton($grid->getModelClass())->getDefaultSearchContext(); $this->context = singleton($grid->getModelClass())->getDefaultSearchContext();
@ -45,19 +47,21 @@ class GridFieldAddExistingSearchHandler extends RequestHandler {
parent::__construct(); parent::__construct();
} }
public function index() { public function index()
{
return $this->renderWith('SilverStripe\\GridFieldExtensions\\GridFieldAddExistingSearchHandler'); return $this->renderWith('SilverStripe\\GridFieldExtensions\\GridFieldAddExistingSearchHandler');
} }
public function add($request) { public function add($request)
if(!$id = $request->postVar('id')) { {
if (!$id = $request->postVar('id')) {
$this->httpError(400); $this->httpError(400);
} }
$list = $this->grid->getList(); $list = $this->grid->getList();
$item = DataList::create($list->dataClass())->byID($id); $item = DataList::create($list->dataClass())->byID($id);
if(!$item) { if (!$item) {
$this->httpError(400); $this->httpError(400);
} }
@ -67,7 +71,8 @@ class GridFieldAddExistingSearchHandler extends RequestHandler {
/** /**
* @return Form * @return Form
*/ */
public function SearchForm() { public function SearchForm()
{
$form = new Form( $form = new Form(
$this, $this,
'SilverStripe\\CMS\\Search\\SearchForm', 'SilverStripe\\CMS\\Search\\SearchForm',
@ -86,7 +91,8 @@ class GridFieldAddExistingSearchHandler extends RequestHandler {
return $form; return $form;
} }
public function doSearch($data, $form) { public function doSearch($data, $form)
{
$list = $this->context->getQuery($data, false, false, $this->getSearchList()); $list = $this->context->getQuery($data, false, false, $this->getSearchList());
$list = $list->subtract($this->grid->getList()); $list = $list->subtract($this->grid->getList());
$list = new PaginatedList($list, $this->request); $list = new PaginatedList($list, $this->request);
@ -98,7 +104,8 @@ class GridFieldAddExistingSearchHandler extends RequestHandler {
return $data->index(); return $data->index();
} }
public function Items() { public function Items()
{
$list = $this->getSearchList(); $list = $this->getSearchList();
$list = $list->subtract($this->grid->getList()); $list = $list->subtract($this->grid->getList());
$list = new PaginatedList($list, $this->request); $list = new PaginatedList($list, $this->request);
@ -106,15 +113,16 @@ class GridFieldAddExistingSearchHandler extends RequestHandler {
return $list; return $list;
} }
public function Link($action = null) { public function Link($action = null)
{
return Controller::join_links($this->grid->Link(), 'add-existing-search', $action); return Controller::join_links($this->grid->Link(), 'add-existing-search', $action);
} }
/** /**
* @return DataList * @return DataList
*/ */
protected function getSearchList() { protected function getSearchList()
{
return $this->button->getSearchList() ?: DataList::create($this->grid->getList()->dataClass()); return $this->button->getSearchList() ?: DataList::create($this->grid->getList()->dataClass());
} }
} }

View File

@ -17,7 +17,8 @@ use SilverStripe\View\Requirements;
/** /**
* Builds on the {@link GridFieldEditableColumns} component to allow creating new records. * Builds on the {@link GridFieldEditableColumns} component to allow creating new records.
*/ */
class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_SaveHandler { class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_SaveHandler
{
private $fragment; private $fragment;
@ -26,7 +27,8 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
/** /**
* @param string $fragment the fragment to render the button in * @param string $fragment the fragment to render the button in
*/ */
public function __construct($fragment = 'buttons-before-left') { public function __construct($fragment = 'buttons-before-left')
{
$this->setFragment($fragment); $this->setFragment($fragment);
$this->setTitle(_t('GridFieldExtensions.ADD', 'Add')); $this->setTitle(_t('GridFieldExtensions.ADD', 'Add'));
} }
@ -36,7 +38,8 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
* *
* @return string * @return string
*/ */
public function getFragment() { public function getFragment()
{
return $this->fragment; return $this->fragment;
} }
@ -46,7 +49,8 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
* @param string $fragment * @param string $fragment
* @return GridFieldAddNewInlineButton $this * @return GridFieldAddNewInlineButton $this
*/ */
public function setFragment($fragment) { public function setFragment($fragment)
{
$this->fragment = $fragment; $this->fragment = $fragment;
return $this; return $this;
} }
@ -56,7 +60,8 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
* *
* @return string * @return string
*/ */
public function getTitle() { public function getTitle()
{
return $this->title; return $this->title;
} }
@ -66,19 +71,21 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
* @param string $title * @param string $title
* @return GridFieldAddNewInlineButton $this * @return GridFieldAddNewInlineButton $this
*/ */
public function setTitle($title) { public function setTitle($title)
{
$this->title = $title; $this->title = $title;
return $this; return $this;
} }
public function getHTMLFragments($grid) { public function getHTMLFragments($grid)
if($grid->getList() && !singleton($grid->getModelClass())->canCreate()) { {
if ($grid->getList() && !singleton($grid->getModelClass())->canCreate()) {
return array(); return array();
} }
$fragment = $this->getFragment(); $fragment = $this->getFragment();
if(!$editable = $grid->getConfig()->getComponentByType('GridFieldEditableColumns')) { if (!$editable = $grid->getConfig()->getComponentByType('GridFieldEditableColumns')) {
throw new Exception('Inline adding requires the editable columns component'); throw new Exception('Inline adding requires the editable columns component');
} }
@ -95,11 +102,12 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
); );
} }
private function getRowTemplate(GridField $grid, GridFieldEditableColumns $editable) { private function getRowTemplate(GridField $grid, GridFieldEditableColumns $editable)
{
$columns = new ArrayList(); $columns = new ArrayList();
$handled = array_keys($editable->getDisplayFields($grid)); $handled = array_keys($editable->getDisplayFields($grid));
if($grid->getList()) { if ($grid->getList()) {
$record = Object::create($grid->getModelClass()); $record = Object::create($grid->getModelClass());
} else { } else {
$record = null; $record = null;
@ -107,11 +115,14 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
$fields = $editable->getFields($grid, $record); $fields = $editable->getFields($grid, $record);
foreach($grid->getColumns() as $column) { foreach ($grid->getColumns() as $column) {
if(in_array($column, $handled)) { if (in_array($column, $handled)) {
$field = $fields->dataFieldByName($column); $field = $fields->dataFieldByName($column);
$field->setName(sprintf( $field->setName(sprintf(
'%s[%s][{%%=o.num%%}][%s]', $grid->getName(), __CLASS__, $field->getName() '%s[%s][{%%=o.num%%}][%s]',
$grid->getName(),
__CLASS__,
$field->getName()
)); ));
$content = $field->Field(); $content = $field->Field();
@ -128,7 +139,7 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
$attrs = ''; $attrs = '';
foreach($grid->getColumnAttributes($record, $column) as $attr => $val) { foreach ($grid->getColumnAttributes($record, $column) as $attr => $val) {
$attrs .= sprintf(' %s="%s"', $attr, Convert::raw2att($val)); $attrs .= sprintf(' %s="%s"', $attr, Convert::raw2att($val));
} }
@ -142,11 +153,12 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
return $columns->renderWith('SilverStripe\\GridFieldExtensions\\GridFieldAddNewInlineRow'); return $columns->renderWith('SilverStripe\\GridFieldExtensions\\GridFieldAddNewInlineRow');
} }
public function handleSave(GridField $grid, DataObjectInterface $record) { public function handleSave(GridField $grid, DataObjectInterface $record)
{
$list = $grid->getList(); $list = $grid->getList();
$value = $grid->Value(); $value = $grid->Value();
if(!isset($value[__CLASS__]) || !is_array($value[__CLASS__])) { if (!isset($value[__CLASS__]) || !is_array($value[__CLASS__])) {
return; return;
} }
@ -157,11 +169,11 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
$sortable = $grid->getConfig()->getComponentByType('SilverStripe\\GridFieldExtensions\\GridFieldOrderableRows'); $sortable = $grid->getConfig()->getComponentByType('SilverStripe\\GridFieldExtensions\\GridFieldOrderableRows');
$form = $editable->getForm($grid, $record); $form = $editable->getForm($grid, $record);
if(!singleton($class)->canCreate()) { if (!singleton($class)->canCreate()) {
return; return;
} }
foreach($value[__CLASS__] as $fields) { foreach ($value[__CLASS__] as $fields) {
$item = $class::create(); $item = $class::create();
$extra = array(); $extra = array();
@ -174,7 +186,7 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
$item->setField($sortField, $fields[$sortField]); $item->setField($sortField, $fields[$sortField]);
} }
if($list instanceof ManyManyList) { if ($list instanceof ManyManyList) {
$extra = array_intersect_key($form->getData(), (array) $list->getExtraFields()); $extra = array_intersect_key($form->getData(), (array) $list->getExtraFields());
} }
@ -182,5 +194,4 @@ class GridFieldAddNewInlineButton implements GridField_HTMLProvider, GridField_S
$list->add($item, $extra); $list->add($item, $extra);
} }
} }
} }

View File

@ -20,7 +20,8 @@ use ReflectionClass;
* By default the list of classes that are createable is the grid field's model class, and any * By default the list of classes that are createable is the grid field's model class, and any
* subclasses. This can be customised using {@link setClasses()}. * subclasses. This can be customised using {@link setClasses()}.
*/ */
class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URLHandler { class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URLHandler
{
private static $allowed_actions = array( private static $allowed_actions = array(
'handleAdd' 'handleAdd'
@ -45,7 +46,8 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
/** /**
* @param string $fragment the fragment to render the button in * @param string $fragment the fragment to render the button in
*/ */
public function __construct($fragment = 'before') { public function __construct($fragment = 'before')
{
$this->setFragment($fragment); $this->setFragment($fragment);
$this->setTitle(_t('GridFieldExtensions.ADD', 'Add')); $this->setTitle(_t('GridFieldExtensions.ADD', 'Add'));
} }
@ -55,7 +57,8 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
* *
* @return string * @return string
*/ */
public function getFragment() { public function getFragment()
{
return $this->fragment; return $this->fragment;
} }
@ -65,7 +68,8 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
* @param string $fragment * @param string $fragment
* @return GridFieldAddNewMultiClass $this * @return GridFieldAddNewMultiClass $this
*/ */
public function setFragment($fragment) { public function setFragment($fragment)
{
$this->fragment = $fragment; $this->fragment = $fragment;
return $this; return $this;
} }
@ -75,7 +79,8 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
* *
* @return string * @return string
*/ */
public function getTitle() { public function getTitle()
{
return $this->title; return $this->title;
} }
@ -85,7 +90,8 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
* @param string $title * @param string $title
* @return GridFieldAddNewMultiClass $this * @return GridFieldAddNewMultiClass $this
*/ */
public function setTitle($title) { public function setTitle($title)
{
$this->title = $title; $this->title = $title;
return $this; return $this;
} }
@ -97,10 +103,11 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
* @param GridField $grid * @param GridField $grid
* @return array a map of class name to title * @return array a map of class name to title
*/ */
public function getClasses(GridField $grid) { public function getClasses(GridField $grid)
{
$result = array(); $result = array();
if(is_null($this->classes)) { if (is_null($this->classes)) {
$classes = array_values(ClassInfo::subclassesFor($grid->getModelClass())); $classes = array_values(ClassInfo::subclassesFor($grid->getModelClass()));
sort($classes); sort($classes);
} else { } else {
@ -108,8 +115,8 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
} }
$kill_ancestors = array(); $kill_ancestors = array();
foreach($classes as $class => $title) { foreach ($classes as $class => $title) {
if(!is_string($class)) { if (!is_string($class)) {
$class = $title; $class = $title;
} }
if (!class_exists($class)) { if (!class_exists($class)) {
@ -124,15 +131,15 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
$kill_ancestors[$ancestor_to_hide] = true; $kill_ancestors[$ancestor_to_hide] = true;
} }
if($is_abstract || !singleton($class)->canCreate()) { if ($is_abstract || !singleton($class)->canCreate()) {
continue; continue;
} }
$result[$class] = $title; $result[$class] = $title;
} }
if($kill_ancestors) { if ($kill_ancestors) {
foreach($kill_ancestors as $class => $bool) { foreach ($kill_ancestors as $class => $bool) {
unset($result[$class]); unset($result[$class]);
} }
} }
@ -146,9 +153,12 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
* @param array $classes a set of class names, optionally mapped to titles * @param array $classes a set of class names, optionally mapped to titles
* @return GridFieldAddNewMultiClass $this * @return GridFieldAddNewMultiClass $this
*/ */
public function setClasses(array $classes, $default = null) { public function setClasses(array $classes, $default = null)
{
$this->classes = $classes; $this->classes = $classes;
if($default) $this->defaultClass = $default; if ($default) {
$this->defaultClass = $default;
}
return $this; return $this;
} }
@ -158,7 +168,8 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
* @param string $default the class name to use as default * @param string $default the class name to use as default
* @return GridFieldAddNewMultiClass $this * @return GridFieldAddNewMultiClass $this
*/ */
public function setDefaultClass($default) { public function setDefaultClass($default)
{
$this->defaultClass = $default; $this->defaultClass = $default;
return $this; return $this;
} }
@ -170,21 +181,27 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
* @return GridFieldAddNewMultiClassHandler * @return GridFieldAddNewMultiClassHandler
*/ */
public function handleAdd($grid, $request) { public function handleAdd($grid, $request)
{
$class = $request->param('ClassName'); $class = $request->param('ClassName');
$classes = $this->getClasses($grid); $classes = $this->getClasses($grid);
$component = $grid->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDetailForm'); $component = $grid->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDetailForm');
if(!$component) { if (!$component) {
throw new Exception('The add new multi class component requires the detail form component.'); throw new Exception('The add new multi class component requires the detail form component.');
} }
if(!$class || !array_key_exists($class, $classes)) { if (!$class || !array_key_exists($class, $classes)) {
throw new HTTPResponse_Exception(400); throw new HTTPResponse_Exception(400);
} }
$handler = Object::create($this->itemRequestClass, $handler = Object::create(
$grid, $component, new $class(), $grid->getForm()->getController(), 'add-multi-class' $this->itemRequestClass,
$grid,
$component,
new $class(),
$grid->getForm()->getController(),
'add-multi-class'
); );
$handler->setTemplate($component->getTemplate()); $handler->setTemplate($component->getTemplate());
@ -194,10 +211,11 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getHTMLFragments($grid) { public function getHTMLFragments($grid)
{
$classes = $this->getClasses($grid); $classes = $this->getClasses($grid);
if(!count($classes)) { if (!count($classes)) {
return array(); return array();
} }
@ -223,13 +241,15 @@ class GridFieldAddNewMultiClass implements GridField_HTMLProvider, GridField_URL
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getURLHandlers($grid) { public function getURLHandlers($grid)
{
return array( return array(
'add-multi-class/$ClassName!' => 'handleAdd' 'add-multi-class/$ClassName!' => 'handleAdd'
); );
} }
public function setItemRequestClass($class) { public function setItemRequestClass($class)
{
$this->itemRequestClass = $class; $this->itemRequestClass = $class;
return $this; return $this;
} }

View File

@ -8,16 +8,19 @@ use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest;
/** /**
* A custom grid field request handler that allows interacting with form fields when adding records. * A custom grid field request handler that allows interacting with form fields when adding records.
*/ */
class GridFieldAddNewMultiClassHandler extends GridFieldDetailForm_ItemRequest { class GridFieldAddNewMultiClassHandler extends GridFieldDetailForm_ItemRequest
{
public function Link($action = null) { public function Link($action = null)
if($this->record->ID) { {
if ($this->record->ID) {
return parent::Link($action); return parent::Link($action);
} else { } else {
return Controller::join_links( return Controller::join_links(
$this->gridField->Link(), 'add-multi-class', get_class($this->record) $this->gridField->Link(),
'add-multi-class',
get_class($this->record)
); );
} }
} }
} }

View File

@ -31,7 +31,8 @@ use SilverStripe\ORM\ManyManyList;
class GridFieldEditableColumns extends GridFieldDataColumns implements class GridFieldEditableColumns extends GridFieldDataColumns implements
GridField_HTMLProvider, GridField_HTMLProvider,
GridField_SaveHandler, GridField_SaveHandler,
GridField_URLHandler { GridField_URLHandler
{
private static $allowed_actions = array( private static $allowed_actions = array(
'handleForm' 'handleForm'
@ -42,15 +43,15 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
*/ */
protected $forms = array(); protected $forms = array();
public function getColumnContent($grid, $record, $col) { public function getColumnContent($grid, $record, $col)
if(!$record->canEdit()) { {
if (!$record->canEdit()) {
return parent::getColumnContent($grid, $record, $col); return parent::getColumnContent($grid, $record, $col);
} }
$fields = $this->getForm($grid, $record)->Fields(); $fields = $this->getForm($grid, $record)->Fields();
if (!$this->displayFields) if (!$this->displayFields) {
{
// If setDisplayFields() not used, utilize $summary_fields // If setDisplayFields() not used, utilize $summary_fields
// in a way similar to base class // in a way similar to base class
$colRelation = explode('.', $col); $colRelation = explode('.', $col);
@ -64,24 +65,21 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
// (ie. Maybe its readonly due to certain circumstances, or removed and not editable) // (ie. Maybe its readonly due to certain circumstances, or removed and not editable)
$cmsFields = $record->getCMSFields(); $cmsFields = $record->getCMSFields();
$cmsField = $cmsFields->dataFieldByName($colRelation[0]); $cmsField = $cmsFields->dataFieldByName($colRelation[0]);
if (!$cmsField || $cmsField->isReadonly() || $cmsField->isDisabled()) if (!$cmsField || $cmsField->isReadonly() || $cmsField->isDisabled()) {
{
return parent::getColumnContent($grid, $record, $col); return parent::getColumnContent($grid, $record, $col);
} }
$field = clone $field; $field = clone $field;
} } else {
else
{
$value = $grid->getDataFieldValue($record, $col); $value = $grid->getDataFieldValue($record, $col);
$rel = (strpos($col,'.') === false); // field references a relation value $rel = (strpos($col, '.') === false); // field references a relation value
$field = ($rel) ? clone $fields->fieldByName($col) : new ReadonlyField($col); $field = ($rel) ? clone $fields->fieldByName($col) : new ReadonlyField($col);
if(!$field) { if (!$field) {
throw new Exception("Could not find the field '$col'"); throw new Exception("Could not find the field '$col'");
} }
} }
if(array_key_exists($col, $this->fieldCasting)) { if (array_key_exists($col, $this->fieldCasting)) {
$value = $grid->getCastedValue($value, $this->fieldCasting[$col]); $value = $grid->getCastedValue($value, $this->fieldCasting[$col]);
} }
@ -97,16 +95,18 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
return $field->forTemplate(); return $field->forTemplate();
} }
public function getHTMLFragments($grid) { public function getHTMLFragments($grid)
{
GridFieldExtensions::include_requirements(); GridFieldExtensions::include_requirements();
$grid->addExtraClass('ss-gridfield-editable'); $grid->addExtraClass('ss-gridfield-editable');
} }
public function handleSave(GridField $grid, DataObjectInterface $record) { public function handleSave(GridField $grid, DataObjectInterface $record)
{
$list = $grid->getList(); $list = $grid->getList();
$value = $grid->Value(); $value = $grid->Value();
if(!isset($value[__CLASS__]) || !is_array($value[__CLASS__])) { if (!isset($value[__CLASS__]) || !is_array($value[__CLASS__])) {
return; return;
} }
@ -115,14 +115,14 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
$form = $this->getForm($grid, $record); $form = $this->getForm($grid, $record);
foreach($value[__CLASS__] as $id => $fields) { foreach ($value[__CLASS__] as $id => $fields) {
if(!is_numeric($id) || !is_array($fields)) { if (!is_numeric($id) || !is_array($fields)) {
continue; continue;
} }
$item = $list->byID($id); $item = $list->byID($id);
if(!$item || !$item->canEdit()) { if (!$item || !$item->canEdit()) {
continue; continue;
} }
@ -137,7 +137,7 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
$item->setField($sortField, $fields[$sortField]); $item->setField($sortField, $fields[$sortField]);
} }
if($list instanceof ManyManyList) { if ($list instanceof ManyManyList) {
$extra = array_intersect_key($form->getData(), (array) $list->getExtraFields()); $extra = array_intersect_key($form->getData(), (array) $list->getExtraFields());
} }
@ -146,28 +146,30 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
} }
} }
public function handleForm(GridField $grid, $request) { public function handleForm(GridField $grid, $request)
{
$id = $request->param('ID'); $id = $request->param('ID');
$list = $grid->getList(); $list = $grid->getList();
if(!ctype_digit($id)) { if (!ctype_digit($id)) {
throw new HTTPResponse_Exception(null, 400); throw new HTTPResponse_Exception(null, 400);
} }
if(!$record = $list->byID($id)) { if (!$record = $list->byID($id)) {
throw new HTTPResponse_Exception(null, 404); throw new HTTPResponse_Exception(null, 404);
} }
$form = $this->getForm($grid, $record); $form = $this->getForm($grid, $record);
foreach($form->Fields() as $field) { foreach ($form->Fields() as $field) {
$field->setName($this->getFieldName($field->getName(), $grid, $record)); $field->setName($this->getFieldName($field->getName(), $grid, $record));
} }
return $form; return $form;
} }
public function getURLHandlers($grid) { public function getURLHandlers($grid)
{
return array( return array(
'editable/form/$ID' => 'handleForm' 'editable/form/$ID' => 'handleForm'
); );
@ -180,22 +182,23 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
* @param DataObjectInterface $record * @param DataObjectInterface $record
* @return FieldList * @return FieldList
*/ */
public function getFields(GridField $grid, DataObjectInterface $record) { public function getFields(GridField $grid, DataObjectInterface $record)
{
$cols = $this->getDisplayFields($grid); $cols = $this->getDisplayFields($grid);
$fields = new FieldList(); $fields = new FieldList();
$list = $grid->getList(); $list = $grid->getList();
$class = $list ? $list->dataClass() : null; $class = $list ? $list->dataClass() : null;
foreach($cols as $col => $info) { foreach ($cols as $col => $info) {
$field = null; $field = null;
if($info instanceof Closure) { if ($info instanceof Closure) {
$field = call_user_func($info, $record, $col, $grid); $field = call_user_func($info, $record, $col, $grid);
} elseif(is_array($info)) { } elseif (is_array($info)) {
if(isset($info['callback'])) { if (isset($info['callback'])) {
$field = call_user_func($info['callback'], $record, $col, $grid); $field = call_user_func($info['callback'], $record, $col, $grid);
} elseif(isset($info['field'])) { } elseif (isset($info['field'])) {
if ($info['field'] == 'SilverStripe\\Forms\\LiteralField') { if ($info['field'] == 'SilverStripe\\Forms\\LiteralField') {
$field = new $info['field']($col, null); $field = new $info['field']($col, null);
} else { } else {
@ -203,7 +206,7 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
} }
} }
if(!$field instanceof FormField) { if (!$field instanceof FormField) {
throw new Exception(sprintf( throw new Exception(sprintf(
'The field for column "%s" is not a valid form field', 'The field for column "%s" is not a valid form field',
$col $col
@ -211,17 +214,16 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
} }
} }
if(!$field && $list instanceof ManyManyList) { if (!$field && $list instanceof ManyManyList) {
$extra = $list->getExtraFields(); $extra = $list->getExtraFields();
if($extra && array_key_exists($col, $extra)) { if ($extra && array_key_exists($col, $extra)) {
$field = Object::create_from_string($extra[$col], $col)->scaffoldFormField(); $field = Object::create_from_string($extra[$col], $col)->scaffoldFormField();
} }
} }
if(!$field) { if (!$field) {
if (!$this->displayFields) if (!$this->displayFields) {
{
// If setDisplayFields() not used, utilize $summary_fields // If setDisplayFields() not used, utilize $summary_fields
// in a way similar to base class // in a way similar to base class
// //
@ -231,27 +233,29 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
// available or is readonly // available or is readonly
// //
$colRelation = explode('.', $col); $colRelation = explode('.', $col);
if($class && $obj = singleton($class)->dbObject($colRelation[0])) { if ($class && $obj = singleton($class)->dbObject($colRelation[0])) {
$field = $obj->scaffoldFormField(); $field = $obj->scaffoldFormField();
} else { } else {
$field = new ReadonlyField($colRelation[0]); $field = new ReadonlyField($colRelation[0]);
} }
} } elseif ($class && $obj = singleton($class)->dbObject($col)) {
else if($class && $obj = singleton($class)->dbObject($col)) {
$field = $obj->scaffoldFormField(); $field = $obj->scaffoldFormField();
} else { } else {
$field = new ReadonlyField($col); $field = new ReadonlyField($col);
} }
} }
if(!$field instanceof FormField) { if (!$field instanceof FormField) {
throw new Exception(sprintf( throw new Exception(sprintf(
'Invalid form field instance for column "%s"', $col 'Invalid form field instance for column "%s"',
$col
)); ));
} }
// Add CSS class for interactive fields // Add CSS class for interactive fields
if (!($field->isReadOnly() || $field instanceof LiteralField)) $field->addExtraClass('editable-column-field'); if (!($field->isReadOnly() || $field instanceof LiteralField)) {
$field->addExtraClass('editable-column-field');
}
$fields->push($field); $fields->push($field);
} }
@ -266,23 +270,30 @@ class GridFieldEditableColumns extends GridFieldDataColumns implements
* @param DataObjectInterface $record * @param DataObjectInterface $record
* @return Form * @return Form
*/ */
public function getForm(GridField $grid, DataObjectInterface $record) { public function getForm(GridField $grid, DataObjectInterface $record)
{
$fields = $this->getFields($grid, $record); $fields = $this->getFields($grid, $record);
$form = new Form($this, null, $fields, new FieldList()); $form = new Form($this, null, $fields, new FieldList());
$form->loadDataFrom($record); $form->loadDataFrom($record);
$form->setFormAction(Controller::join_links( $form->setFormAction(Controller::join_links(
$grid->Link(), 'editable/form', $record->ID $grid->Link(),
'editable/form',
$record->ID
)); ));
return $form; return $form;
} }
protected function getFieldName($name, GridField $grid, DataObjectInterface $record) { protected function getFieldName($name, GridField $grid, DataObjectInterface $record)
{
return sprintf( return sprintf(
'%s[%s][%s][%s]', $grid->getName(), __CLASS__, $record->ID, $name '%s[%s][%s][%s]',
$grid->getName(),
__CLASS__,
$record->ID,
$name
); );
} }
} }

View File

@ -7,16 +7,18 @@ use SilverStripe\View\Requirements;
/** /**
* Utility functions for the grid fields extension module. * Utility functions for the grid fields extension module.
*/ */
class GridFieldExtensions { class GridFieldExtensions
{
public static function include_requirements() { public static function include_requirements()
{
$moduleDir = self::get_module_dir(); $moduleDir = self::get_module_dir();
Requirements::css($moduleDir.'/css/GridFieldExtensions.css'); Requirements::css($moduleDir.'/css/GridFieldExtensions.css');
Requirements::javascript($moduleDir.'/javascript/GridFieldExtensions.js'); Requirements::javascript($moduleDir.'/javascript/GridFieldExtensions.js');
} }
public static function get_module_dir() { public static function get_module_dir()
{
return basename(dirname(__DIR__)); return basename(dirname(__DIR__));
} }
} }

View File

@ -8,7 +8,8 @@ use SilverStripe\View\ArrayData;
/** /**
* Displays a link to an external source referenced 'external link' * Displays a link to an external source referenced 'external link'
*/ */
class GridFieldExternalLink extends GridFieldDataColumns { class GridFieldExternalLink extends GridFieldDataColumns
{
/** /**
* Add a column for the actions * Add a column for the actions
@ -16,8 +17,11 @@ class GridFieldExternalLink extends GridFieldDataColumns {
* @param type $gridField * @param type $gridField
* @param array $columns * @param array $columns
*/ */
public function augmentColumns($gridField, &$columns) { public function augmentColumns($gridField, &$columns)
if(!in_array('Actions', $columns)) $columns[] = 'Actions'; {
if (!in_array('Actions', $columns)) {
$columns[] = 'Actions';
}
} }
/** /**
@ -28,7 +32,8 @@ class GridFieldExternalLink extends GridFieldDataColumns {
* @param string $columnName * @param string $columnName
* @return array * @return array
*/ */
public function getColumnAttributes($gridField, $record, $columnName) { public function getColumnAttributes($gridField, $record, $columnName)
{
return array('class' => 'col-buttons'); return array('class' => 'col-buttons');
} }
@ -39,8 +44,9 @@ class GridFieldExternalLink extends GridFieldDataColumns {
* @param string $columnName * @param string $columnName
* @return array * @return array
*/ */
public function getColumnMetadata($gridField, $columnName) { public function getColumnMetadata($gridField, $columnName)
if($columnName == 'Actions') { {
if ($columnName == 'Actions') {
return array('title' => ''); return array('title' => '');
} }
return array(); return array();
@ -52,7 +58,8 @@ class GridFieldExternalLink extends GridFieldDataColumns {
* @param type $gridField * @param type $gridField
* @return type * @return type
*/ */
public function getColumnsHandled($gridField) { public function getColumnsHandled($gridField)
{
return array('Actions'); return array('Actions');
} }
@ -63,7 +70,8 @@ class GridFieldExternalLink extends GridFieldDataColumns {
* *
* @return string - the HTML for the column * @return string - the HTML for the column
*/ */
public function getColumnContent($gridField, $record, $columnName) { public function getColumnContent($gridField, $record, $columnName)
{
$data = new ArrayData(array( $data = new ArrayData(array(
'Link' => $record->hasMethod('getExternalLink') ? $record->getExternalLink() : $record->ExternalLink, 'Link' => $record->hasMethod('getExternalLink') ? $record->getExternalLink() : $record->ExternalLink,
'Text' => $record->hasMethod('getExternalLinkText') ? $record->getExternalLinkText() : 'External Link' 'Text' => $record->hasMethod('getExternalLinkText') ? $record->getExternalLinkText() : 'External Link'

View File

@ -33,7 +33,8 @@ class GridFieldOrderableRows extends RequestHandler implements
GridField_DataManipulator, GridField_DataManipulator,
GridField_HTMLProvider, GridField_HTMLProvider,
GridField_URLHandler, GridField_URLHandler,
GridField_SaveHandler { GridField_SaveHandler
{
/** /**
* @see $immediateUpdate * @see $immediateUpdate
@ -82,7 +83,8 @@ class GridFieldOrderableRows extends RequestHandler implements
/** /**
* @param string $sortField * @param string $sortField
*/ */
public function __construct($sortField = 'Sort') { public function __construct($sortField = 'Sort')
{
parent::__construct(); parent::__construct();
$this->sortField = $sortField; $this->sortField = $sortField;
$this->immediateUpdate = $this->config()->default_immediate_update; $this->immediateUpdate = $this->config()->default_immediate_update;
@ -91,7 +93,8 @@ class GridFieldOrderableRows extends RequestHandler implements
/** /**
* @return string * @return string
*/ */
public function getSortField() { public function getSortField()
{
return $this->sortField; return $this->sortField;
} }
@ -101,7 +104,8 @@ class GridFieldOrderableRows extends RequestHandler implements
* @param string $sortField * @param string $sortField
* @return GridFieldOrderableRows $this * @return GridFieldOrderableRows $this
*/ */
public function setSortField($field) { public function setSortField($field)
{
$this->sortField = $field; $this->sortField = $field;
return $this; return $this;
} }
@ -109,7 +113,8 @@ class GridFieldOrderableRows extends RequestHandler implements
/** /**
* @return boolean * @return boolean
*/ */
public function getImmediateUpdate() { public function getImmediateUpdate()
{
return $this->immediateUpdate; return $this->immediateUpdate;
} }
@ -118,7 +123,8 @@ class GridFieldOrderableRows extends RequestHandler implements
* @param boolean $immediateUpdate * @param boolean $immediateUpdate
* @return GridFieldOrderableRows $this * @return GridFieldOrderableRows $this
*/ */
public function setImmediateUpdate($bool) { public function setImmediateUpdate($bool)
{
$this->immediateUpdate = $bool; $this->immediateUpdate = $bool;
return $this; return $this;
} }
@ -126,7 +132,8 @@ class GridFieldOrderableRows extends RequestHandler implements
/** /**
* @return string|array * @return string|array
*/ */
public function getExtraSortFields() { public function getExtraSortFields()
{
return $this->extraSortFields; return $this->extraSortFields;
} }
@ -136,7 +143,8 @@ class GridFieldOrderableRows extends RequestHandler implements
* @param string|array $fields * @param string|array $fields
* @return GridFieldOrderableRows $this * @return GridFieldOrderableRows $this
*/ */
public function setExtraSortFields($fields) { public function setExtraSortFields($fields)
{
$this->extraSortFields = $fields; $this->extraSortFields = $fields;
return $this; return $this;
} }
@ -144,7 +152,8 @@ class GridFieldOrderableRows extends RequestHandler implements
/** /**
* @return int * @return int
*/ */
public function getReorderColumnNumber() { public function getReorderColumnNumber()
{
return $this->reorderColumnNumber; return $this->reorderColumnNumber;
} }
@ -154,7 +163,8 @@ class GridFieldOrderableRows extends RequestHandler implements
* @param int $colno * @param int $colno
* @return GridFieldOrderableRows $this * @return GridFieldOrderableRows $this
*/ */
public function setReorderColumnNumber($colno) { public function setReorderColumnNumber($colno)
{
$this->reorderColumnNumber = $colno; $this->reorderColumnNumber = $colno;
return $this; return $this;
} }
@ -165,22 +175,23 @@ class GridFieldOrderableRows extends RequestHandler implements
* @param DataList $list * @param DataList $list
* @return string * @return string
*/ */
public function getSortTable(SS_List $list) { public function getSortTable(SS_List $list)
{
$field = $this->getSortField(); $field = $this->getSortField();
if($list instanceof ManyManyList) { if ($list instanceof ManyManyList) {
$extra = $list->getExtraFields(); $extra = $list->getExtraFields();
$table = $list->getJoinTable(); $table = $list->getJoinTable();
if($extra && array_key_exists($field, $extra)) { if ($extra && array_key_exists($field, $extra)) {
return $table; return $table;
} }
} }
$classes = ClassInfo::dataClassesFor($list->dataClass()); $classes = ClassInfo::dataClassesFor($list->dataClass());
foreach($classes as $class) { foreach ($classes as $class) {
if(singleton($class)->hasDataBaseField($field)) { if (singleton($class)->hasDataBaseField($field)) {
return $class; return $class;
} }
} }
@ -188,7 +199,8 @@ class GridFieldOrderableRows extends RequestHandler implements
throw new Exception("Couldn't find the sort field '$field'"); throw new Exception("Couldn't find the sort field '$field'");
} }
public function getURLHandlers($grid) { public function getURLHandlers($grid)
{
return array( return array(
'POST reorder' => 'handleReorder', 'POST reorder' => 'handleReorder',
'POST movetopage' => 'handleMoveToPage' 'POST movetopage' => 'handleMoveToPage'
@ -198,7 +210,8 @@ class GridFieldOrderableRows extends RequestHandler implements
/** /**
* @param GridField $field * @param GridField $field
*/ */
public function getHTMLFragments($field) { public function getHTMLFragments($field)
{
GridFieldExtensions::include_requirements(); GridFieldExtensions::include_requirements();
$field->addExtraClass('ss-gridfield-orderable'); $field->addExtraClass('ss-gridfield-orderable');
@ -207,17 +220,20 @@ class GridFieldOrderableRows extends RequestHandler implements
$field->setAttribute('data-url-movetopage', $field->Link('movetopage')); $field->setAttribute('data-url-movetopage', $field->Link('movetopage'));
} }
public function augmentColumns($grid, &$cols) { public function augmentColumns($grid, &$cols)
if(!in_array('Reorder', $cols) && $grid->getState()->GridFieldOrderableRows->enabled) { {
if (!in_array('Reorder', $cols) && $grid->getState()->GridFieldOrderableRows->enabled) {
array_splice($cols, $this->reorderColumnNumber, 0, 'Reorder'); array_splice($cols, $this->reorderColumnNumber, 0, 'Reorder');
} }
} }
public function getColumnsHandled($grid) { public function getColumnsHandled($grid)
{
return array('Reorder'); return array('Reorder');
} }
public function getColumnContent($grid, $record, $col) { public function getColumnContent($grid, $record, $col)
{
// In case you are using GridFieldEditableColumns, this ensures that // In case you are using GridFieldEditableColumns, this ensures that
// the correct sort order is saved. If you are not using that component, // the correct sort order is saved. If you are not using that component,
// this will be ignored by other components, but will still work for this. // this will be ignored by other components, but will still work for this.
@ -236,11 +252,13 @@ class GridFieldOrderableRows extends RequestHandler implements
))->renderWith('SilverStripe\\GridFieldExtensions\\GridFieldOrderableRowsDragHandle'); ))->renderWith('SilverStripe\\GridFieldExtensions\\GridFieldOrderableRowsDragHandle');
} }
public function getColumnAttributes($grid, $record, $col) { public function getColumnAttributes($grid, $record, $col)
{
return array('class' => 'col-reorder'); return array('class' => 'col-reorder');
} }
public function getColumnMetadata($grid, $col) { public function getColumnMetadata($grid, $col)
{
if ($fieldLabels = singleton($grid->getModelClass())->fieldLabels()) { if ($fieldLabels = singleton($grid->getModelClass())->fieldLabels()) {
return array('title' => isset($fieldLabels['Reorder']) ? $fieldLabels['Reorder'] : ''); return array('title' => isset($fieldLabels['Reorder']) ? $fieldLabels['Reorder'] : '');
} }
@ -248,7 +266,8 @@ class GridFieldOrderableRows extends RequestHandler implements
return array('title' => ''); return array('title' => '');
} }
public function getManipulatedData(GridField $grid, SS_List $list) { public function getManipulatedData(GridField $grid, SS_List $list)
{
$state = $grid->getState(); $state = $grid->getState();
$sorted = (bool) ((string) $state->GridFieldSortableHeader->SortColumn); $sorted = (bool) ((string) $state->GridFieldSortableHeader->SortColumn);
@ -256,11 +275,11 @@ class GridFieldOrderableRows extends RequestHandler implements
// sort column, otherwise disable reordering. // sort column, otherwise disable reordering.
$state->GridFieldOrderableRows->enabled = !$sorted; $state->GridFieldOrderableRows->enabled = !$sorted;
if(!$sorted) { if (!$sorted) {
$sortterm = ''; $sortterm = '';
if ($this->extraSortFields) { if ($this->extraSortFields) {
if (is_array($this->extraSortFields)) { if (is_array($this->extraSortFields)) {
foreach($this->extraSortFields as $col => $dir) { foreach ($this->extraSortFields as $col => $dir) {
$sortterm .= "$col $dir, "; $sortterm .= "$col $dir, ";
} }
} else { } else {
@ -286,21 +305,21 @@ class GridFieldOrderableRows extends RequestHandler implements
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
* @return SS_HTTPResponse * @return SS_HTTPResponse
*/ */
public function handleReorder($grid, $request) { public function handleReorder($grid, $request)
if (!$this->immediateUpdate)
{ {
if (!$this->immediateUpdate) {
$this->httpError(400); $this->httpError(400);
} }
$list = $grid->getList(); $list = $grid->getList();
$modelClass = $grid->getModelClass(); $modelClass = $grid->getModelClass();
if ($list instanceof ManyManyList && !singleton($modelClass)->canView()) { if ($list instanceof ManyManyList && !singleton($modelClass)->canView()) {
$this->httpError(403); $this->httpError(403);
} else if(!($list instanceof ManyManyList) && !singleton($modelClass)->canEdit()) { } elseif (!($list instanceof ManyManyList) && !singleton($modelClass)->canEdit()) {
$this->httpError(403); $this->httpError(403);
} }
// Save any un-committed changes to the gridfield // Save any un-committed changes to the gridfield
if(($form = $grid->getForm()) && ($record = $form->getRecord()) ) { if (($form = $grid->getForm()) && ($record = $form->getRecord())) {
$form->loadDataFrom($request->requestVars(), true); $form->loadDataFrom($request->requestVars(), true);
$grid->saveInto($record); $grid->saveInto($record);
} }
@ -308,8 +327,7 @@ class GridFieldOrderableRows extends RequestHandler implements
// Get records from the `GridFieldEditableColumns` column // Get records from the `GridFieldEditableColumns` column
$data = $request->postVar($grid->getName()); $data = $request->postVar($grid->getName());
$sortedIDs = $this->getSortedIDs($data); $sortedIDs = $this->getSortedIDs($data);
if (!$this->executeReorder($grid, $sortedIDs)) if (!$this->executeReorder($grid, $sortedIDs)) {
{
$this->httpError(400); $this->httpError(400);
} }
@ -323,13 +341,14 @@ class GridFieldOrderableRows extends RequestHandler implements
* @param array $data Raw posted data * @param array $data Raw posted data
* @return array * @return array
*/ */
protected function getSortedIDs($data) { protected function getSortedIDs($data)
{
if (empty($data['GridFieldEditableColumns'])) { if (empty($data['GridFieldEditableColumns'])) {
return array(); return array();
} }
$sortedIDs = array(); $sortedIDs = array();
foreach($data['GridFieldEditableColumns'] as $id => $recordData) { foreach ($data['GridFieldEditableColumns'] as $id => $recordData) {
$sortValue = $recordData[$this->sortField]; $sortValue = $recordData[$this->sortField];
$sortedIDs[$sortValue] = $id; $sortedIDs[$sortValue] = $id;
} }
@ -340,8 +359,9 @@ class GridFieldOrderableRows extends RequestHandler implements
/** /**
* Handles requests to move an item to the previous or next page. * Handles requests to move an item to the previous or next page.
*/ */
public function handleMoveToPage(GridField $grid, $request) { public function handleMoveToPage(GridField $grid, $request)
if(!$paginator = $grid->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldPaginator')) { {
if (!$paginator = $grid->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldPaginator')) {
$this->httpError(404, 'Paginator component not found'); $this->httpError(404, 'Paginator component not found');
} }
@ -358,7 +378,7 @@ class GridFieldOrderableRows extends RequestHandler implements
$id = isset($move['id']) ? (int) $move['id'] : null; $id = isset($move['id']) ? (int) $move['id'] : null;
$to = isset($move['page']) ? $move['page'] : null; $to = isset($move['page']) ? $move['page'] : null;
if(!isset($values[$id])) { if (!isset($values[$id])) {
$this->httpError(400, 'Invalid item ID'); $this->httpError(400, 'Invalid item ID');
} }
@ -367,22 +387,26 @@ class GridFieldOrderableRows extends RequestHandler implements
$page = ((int) $grid->getState()->GridFieldPaginator->currentPage) ?: 1; $page = ((int) $grid->getState()->GridFieldPaginator->currentPage) ?: 1;
$per = $paginator->getItemsPerPage(); $per = $paginator->getItemsPerPage();
if($to == 'prev') { if ($to == 'prev') {
$swap = $list->limit(1, ($page - 1) * $per - 1)->first(); $swap = $list->limit(1, ($page - 1) * $per - 1)->first();
$values[$swap->ID] = $swap->$field; $values[$swap->ID] = $swap->$field;
$order[] = $id; $order[] = $id;
$order[] = $swap->ID; $order[] = $swap->ID;
foreach($existing as $_id => $sort) { foreach ($existing as $_id => $sort) {
if($id != $_id) $order[] = $_id; if ($id != $_id) {
$order[] = $_id;
} }
} elseif($to == 'next') { }
} elseif ($to == 'next') {
$swap = $list->limit(1, $page * $per)->first(); $swap = $list->limit(1, $page * $per)->first();
$values[$swap->ID] = $swap->$field; $values[$swap->ID] = $swap->$field;
foreach($existing as $_id => $sort) { foreach ($existing as $_id => $sort) {
if($id != $_id) $order[] = $_id; if ($id != $_id) {
$order[] = $_id;
}
} }
$order[] = $swap->ID; $order[] = $swap->ID;
@ -400,9 +424,9 @@ class GridFieldOrderableRows extends RequestHandler implements
* Handle saving when 'immediateUpdate' is disabled, otherwise this isn't * Handle saving when 'immediateUpdate' is disabled, otherwise this isn't
* necessary for the default sort mode. * necessary for the default sort mode.
*/ */
public function handleSave(GridField $grid, DataObjectInterface $record) { public function handleSave(GridField $grid, DataObjectInterface $record)
if (!$this->immediateUpdate)
{ {
if (!$this->immediateUpdate) {
$value = $grid->Value(); $value = $grid->Value();
$sortedIDs = $this->getSortedIDs($value); $sortedIDs = $this->getSortedIDs($value);
if ($sortedIDs) { if ($sortedIDs) {
@ -416,8 +440,9 @@ class GridFieldOrderableRows extends RequestHandler implements
* @param array $sortedIDs List of IDS, where the key is the sort field value to save * @param array $sortedIDs List of IDS, where the key is the sort field value to save
* @return bool * @return bool
*/ */
protected function executeReorder(GridField $grid, $sortedIDs) { protected function executeReorder(GridField $grid, $sortedIDs)
if(!is_array($sortedIDs)) { {
if (!is_array($sortedIDs)) {
return false; return false;
} }
$field = $this->getSortField(); $field = $this->getSortField();
@ -425,7 +450,7 @@ class GridFieldOrderableRows extends RequestHandler implements
$sortterm = ''; $sortterm = '';
if ($this->extraSortFields) { if ($this->extraSortFields) {
if (is_array($this->extraSortFields)) { if (is_array($this->extraSortFields)) {
foreach($this->extraSortFields as $col => $dir) { foreach ($this->extraSortFields as $col => $dir) {
$sortterm .= "$col $dir, "; $sortterm .= "$col $dir, ";
} }
} else { } else {
@ -437,7 +462,7 @@ class GridFieldOrderableRows extends RequestHandler implements
$items = $list->filter('ID', $sortedIDs)->sort($sortterm); $items = $list->filter('ID', $sortedIDs)->sort($sortterm);
// Ensure that each provided ID corresponded to an actual object. // Ensure that each provided ID corresponded to an actual object.
if(count($items) != count($sortedIDs)) { if (count($items) != count($sortedIDs)) {
return false; return false;
} }
@ -445,11 +470,9 @@ class GridFieldOrderableRows extends RequestHandler implements
$this->populateSortValues($items); $this->populateSortValues($items);
// Generate the current sort values. // Generate the current sort values.
if ($items instanceof ManyManyList) if ($items instanceof ManyManyList) {
{
$current = array(); $current = array();
foreach ($items->toArray() as $record) foreach ($items->toArray() as $record) {
{
// NOTE: _SortColumn0 is the first ->sort() field // NOTE: _SortColumn0 is the first ->sort() field
// used by SS when functions are detected in a SELECT // used by SS when functions are detected in a SELECT
// or CASE WHEN. // or CASE WHEN.
@ -459,9 +482,7 @@ class GridFieldOrderableRows extends RequestHandler implements
$current[$record->ID] = $record->$field; $current[$record->ID] = $record->$field;
} }
} }
} } else {
else
{
$current = $items->map('ID', $field)->toArray(); $current = $items->map('ID', $field)->toArray();
} }
@ -470,7 +491,8 @@ class GridFieldOrderableRows extends RequestHandler implements
return true; return true;
} }
protected function reorderItems($list, array $values, array $sortedIDs) { protected function reorderItems($list, array $values, array $sortedIDs)
{
$sortField = $this->getSortField(); $sortField = $this->getSortField();
/** @var SS_List $map */ /** @var SS_List $map */
$map = $list->map('ID', $sortField); $map = $list->map('ID', $sortField);
@ -491,8 +513,8 @@ class GridFieldOrderableRows extends RequestHandler implements
if (!$isVersioned) { if (!$isVersioned) {
$sortTable = $this->getSortTable($list); $sortTable = $this->getSortTable($list);
$additionalSQL = (!$list instanceof ManyManyList) ? ', "LastEdited" = NOW()' : ''; $additionalSQL = (!$list instanceof ManyManyList) ? ', "LastEdited" = NOW()' : '';
foreach($sortedIDs as $sortValue => $id) { foreach ($sortedIDs as $sortValue => $id) {
if($map[$id] != $sortValue) { if ($map[$id] != $sortValue) {
DB::query(sprintf( DB::query(sprintf(
'UPDATE "%s" SET "%s" = %d%s WHERE %s', 'UPDATE "%s" SET "%s" = %d%s WHERE %s',
$sortTable, $sortTable,
@ -508,8 +530,8 @@ class GridFieldOrderableRows extends RequestHandler implements
// *_versions table is updated. This ensures re-ordering works // *_versions table is updated. This ensures re-ordering works
// similar to the SiteTree where you change the position, and then // similar to the SiteTree where you change the position, and then
// you go into the record and publish it. // you go into the record and publish it.
foreach($sortedIDs as $sortValue => $id) { foreach ($sortedIDs as $sortValue => $id) {
if($map[$id] != $sortValue) { if ($map[$id] != $sortValue) {
$record = $class::get()->byID($id); $record = $class::get()->byID($id);
$record->$sortField = $sortValue; $record->$sortField = $sortValue;
$record->write(); $record->write();
@ -520,14 +542,15 @@ class GridFieldOrderableRows extends RequestHandler implements
$this->extend('onAfterReorderItems', $list); $this->extend('onAfterReorderItems', $list);
} }
protected function populateSortValues(DataList $list) { protected function populateSortValues(DataList $list)
{
$list = clone $list; $list = clone $list;
$field = $this->getSortField(); $field = $this->getSortField();
$table = $this->getSortTable($list); $table = $this->getSortTable($list);
$clause = sprintf('"%s"."%s" = 0', $table, $this->getSortField()); $clause = sprintf('"%s"."%s" = 0', $table, $this->getSortField());
$additionalSQL = (!$list instanceof ManyManyList) ? ', "LastEdited" = NOW()' : ''; $additionalSQL = (!$list instanceof ManyManyList) ? ', "LastEdited" = NOW()' : '';
foreach($list->where($clause)->column('ID') as $id) { foreach ($list->where($clause)->column('ID') as $id) {
$max = DB::query(sprintf('SELECT MAX("%s") + 1 FROM "%s"', $field, $table)); $max = DB::query(sprintf('SELECT MAX("%s") + 1 FROM "%s"', $field, $table));
$max = $max->value(); $max = $max->value();
@ -542,20 +565,21 @@ class GridFieldOrderableRows extends RequestHandler implements
} }
} }
protected function getSortTableClauseForIds(DataList $list, $ids) { protected function getSortTableClauseForIds(DataList $list, $ids)
if(is_array($ids)) { {
if (is_array($ids)) {
$value = 'IN (' . implode(', ', array_map('intval', $ids)) . ')'; $value = 'IN (' . implode(', ', array_map('intval', $ids)) . ')';
} else { } else {
$value = '= ' . (int) $ids; $value = '= ' . (int) $ids;
} }
if($list instanceof ManyManyList) { if ($list instanceof ManyManyList) {
$extra = $list->getExtraFields(); $extra = $list->getExtraFields();
$key = $list->getLocalKey(); $key = $list->getLocalKey();
$foreignKey = $list->getForeignKey(); $foreignKey = $list->getForeignKey();
$foreignID = (int) $list->getForeignID(); $foreignID = (int) $list->getForeignID();
if($extra && array_key_exists($this->getSortField(), $extra)) { if ($extra && array_key_exists($this->getSortField(), $extra)) {
return sprintf( return sprintf(
'"%s" %s AND "%s" = %d', '"%s" %s AND "%s" = %d',
$key, $key,
@ -568,5 +592,4 @@ class GridFieldOrderableRows extends RequestHandler implements
return "\"ID\" $value"; return "\"ID\" $value";
} }
} }

View File

@ -22,7 +22,8 @@ use SilverStripe\ORM\ArrayList;
* as tabs, breadcrumbs and a back link. Much of this code is extracted from the * as tabs, breadcrumbs and a back link. Much of this code is extracted from the
* detail form. * detail form.
*/ */
abstract class GridFieldRequestHandler extends RequestHandler { abstract class GridFieldRequestHandler extends RequestHandler
{
private static $allowed_actions = array( private static $allowed_actions = array(
'Form' 'Form'
@ -48,7 +49,8 @@ abstract class GridFieldRequestHandler extends RequestHandler {
*/ */
protected $template = __CLASS__; protected $template = __CLASS__;
public function __construct(GridField $grid, GridFieldComponent $component, $name) { public function __construct(GridField $grid, GridFieldComponent $component, $name)
{
$this->grid = $grid; $this->grid = $grid;
$this->component = $component; $this->component = $component;
$this->name = $name; $this->name = $name;
@ -56,10 +58,11 @@ abstract class GridFieldRequestHandler extends RequestHandler {
parent::__construct(); parent::__construct();
} }
public function index($request) { public function index($request)
{
$result = $this->renderWith($this->template); $result = $this->renderWith($this->template);
if($request->isAjax()) { if ($request->isAjax()) {
return $result; return $result;
} else { } else {
return $this->getTopLevelController()->customise(array( return $this->getTopLevelController()->customise(array(
@ -68,7 +71,8 @@ abstract class GridFieldRequestHandler extends RequestHandler {
} }
} }
public function Link($action = null) { public function Link($action = null)
{
return Controller::join_links($this->grid->Link(), $this->name, $action); return Controller::join_links($this->grid->Link(), $this->name, $action);
} }
@ -77,7 +81,8 @@ abstract class GridFieldRequestHandler extends RequestHandler {
* *
* @return Form * @return Form
*/ */
public function Form() { public function Form()
{
$form = new Form( $form = new Form(
$this, $this,
'SilverStripe\\Forms\\Form', 'SilverStripe\\Forms\\Form',
@ -85,7 +90,7 @@ abstract class GridFieldRequestHandler extends RequestHandler {
new FieldList() new FieldList()
); );
if($this->getTopLevelController() instanceof LeftAndMain) { if ($this->getTopLevelController() instanceof LeftAndMain) {
$form->setTemplate('LeftAndMain_EditForm'); $form->setTemplate('LeftAndMain_EditForm');
$form->addExtraClass('cms-content cms-edit-form cms-tabset center'); $form->addExtraClass('cms-content cms-edit-form cms-tabset center');
$form->setAttribute('data-pjax-fragment', 'CurrentForm Content'); $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
@ -100,31 +105,35 @@ abstract class GridFieldRequestHandler extends RequestHandler {
/** /**
* @return Controller * @return Controller
*/ */
public function getController() { public function getController()
{
return $this->grid->getForm()->getController(); return $this->grid->getForm()->getController();
} }
/** /**
* @param string $template * @param string $template
*/ */
public function setTemplate($template) { public function setTemplate($template)
{
$this->template = $template; $this->template = $template;
} }
/** /**
* @return string * @return string
*/ */
public function getTemplate() { public function getTemplate()
{
return $this->template; return $this->template;
} }
/** /**
* @return ArrayList * @return ArrayList
*/ */
public function getBreadcrumbs() { public function getBreadcrumbs()
{
$controller = $this->getController(); $controller = $this->getController();
if($controller->hasMethod('Breadcrumbs')) { if ($controller->hasMethod('Breadcrumbs')) {
return $controller->Breadcrumbs(); return $controller->Breadcrumbs();
} else { } else {
return new ArrayList(); return new ArrayList();
@ -134,10 +143,11 @@ abstract class GridFieldRequestHandler extends RequestHandler {
/** /**
* @return string * @return string
*/ */
protected function getBackLink() { protected function getBackLink()
{
$controller = $this->getTopLevelController(); $controller = $this->getTopLevelController();
if($controller->hasMethod('Backlink')) { if ($controller->hasMethod('Backlink')) {
return $controller->Backlink(); return $controller->Backlink();
} else { } else {
return $controller->Link(); return $controller->Link();
@ -147,13 +157,14 @@ abstract class GridFieldRequestHandler extends RequestHandler {
/** /**
* @return Controller * @return Controller
*/ */
protected function getTopLevelController() { protected function getTopLevelController()
{
$controller = $this->getController(); $controller = $this->getController();
while($controller) { while ($controller) {
if($controller instanceof GridFieldRequestHandler) { if ($controller instanceof GridFieldRequestHandler) {
$controller = $controller->getController(); $controller = $controller->getController();
} elseif($controller instanceof GridFieldDetailForm_ItemRequest) { } elseif ($controller instanceof GridFieldDetailForm_ItemRequest) {
$controller = $controller->getController(); $controller = $controller->getController();
} else { } else {
break; break;
@ -162,5 +173,4 @@ abstract class GridFieldRequestHandler extends RequestHandler {
return $controller; return $controller;
} }
} }

View File

@ -9,9 +9,11 @@ use SilverStripe\View\ArrayData;
/** /**
* A simple header which displays column titles. * A simple header which displays column titles.
*/ */
class GridFieldTitleHeader implements GridField_HTMLProvider { class GridFieldTitleHeader implements GridField_HTMLProvider
{
public function getHTMLFragments($grid) { public function getHTMLFragments($grid)
{
$cols = new ArrayList(); $cols = new ArrayList();
foreach ($grid->getColumns() as $name) { foreach ($grid->getColumns() as $name) {
@ -27,5 +29,4 @@ class GridFieldTitleHeader implements GridField_HTMLProvider {
'header' => $cols->renderWith(__CLASS__) 'header' => $cols->renderWith(__CLASS__)
); );
} }
} }

View File

@ -8,9 +8,11 @@ use SilverStripe\GridFieldExtensions\GridFieldAddNewMultiClass;
/** /**
* Tests for {@link GridFieldAddNewMultiClass}. * Tests for {@link GridFieldAddNewMultiClass}.
*/ */
class GridFieldAddNewMultiClassTest extends SapphireTest { class GridFieldAddNewMultiClassTest extends SapphireTest
{
public function testGetClasses() { public function testGetClasses()
{
$grid = new GridField('TestGridField'); $grid = new GridField('TestGridField');
$grid->setModelClass('GridFieldAddNewMultiClassTest_A'); $grid->setModelClass('GridFieldAddNewMultiClassTest_A');
@ -40,25 +42,31 @@ class GridFieldAddNewMultiClassTest extends SapphireTest {
'Sorting and custom titles can be specified' 'Sorting and custom titles can be specified'
); );
} }
} }
/**#@+ /**#@+
* @ignore * @ignore
*/ */
class GridFieldAddNewMultiClassTest_A implements TestOnly { class GridFieldAddNewMultiClassTest_A implements TestOnly
public function i18n_singular_name() { {
public function i18n_singular_name()
{
$class = get_class($this); $class = get_class($this);
return substr($class, strpos($class, '_') + 1); return substr($class, strpos($class, '_') + 1);
} }
public function canCreate() { public function canCreate()
{
return true; return true;
} }
} }
class GridFieldAddNewMultiClassTest_B extends GridFieldAddNewMultiClassTest_A implements TestOnly {} class GridFieldAddNewMultiClassTest_B extends GridFieldAddNewMultiClassTest_A implements TestOnly
class GridFieldAddNewMultiClassTest_C extends GridFieldAddNewMultiClassTest_A implements TestOnly {} {
}
class GridFieldAddNewMultiClassTest_C extends GridFieldAddNewMultiClassTest_A implements TestOnly
{
}
/**#@-*/ /**#@-*/

View File

@ -10,7 +10,8 @@ use SilverStripe\ORM\DataObject;
/** /**
* Tests for the {@link GridFieldOrderableRows} component. * Tests for the {@link GridFieldOrderableRows} component.
*/ */
class GridFieldOrderableRowsTest extends SapphireTest { class GridFieldOrderableRowsTest extends SapphireTest
{
protected $usesDatabase = true; protected $usesDatabase = true;
@ -28,7 +29,8 @@ class GridFieldOrderableRowsTest extends SapphireTest {
$this->markTestSkipped('Upgrade to 4.0: Needs to be re-implemented.'); $this->markTestSkipped('Upgrade to 4.0: Needs to be re-implemented.');
} }
public function testReorderItems() { public function testReorderItems()
{
$orderable = new GridFieldOrderableRows('ManyManySort'); $orderable = new GridFieldOrderableRows('ManyManySort');
$reflection = new ReflectionMethod($orderable, 'executeReorder'); $reflection = new ReflectionMethod($orderable, 'executeReorder');
$reflection->setAccessible(true); $reflection->setAccessible(true);
@ -49,7 +51,7 @@ class GridFieldOrderableRowsTest extends SapphireTest {
$desiredOrder = array(); $desiredOrder = array();
// Make order non-contiguous, and 1-based // Make order non-contiguous, and 1-based
foreach(array_reverse($originalOrder) as $index => $id) { foreach (array_reverse($originalOrder) as $index => $id) {
$desiredOrder[$index * 2 + 1] = $id; $desiredOrder[$index * 2 + 1] = $id;
} }
@ -60,13 +62,13 @@ class GridFieldOrderableRowsTest extends SapphireTest {
$newOrder = $parent->MyManyMany()->sort('ManyManySort')->map('ManyManySort', 'ID')->toArray(); $newOrder = $parent->MyManyMany()->sort('ManyManySort')->map('ManyManySort', 'ID')->toArray();
$this->assertEquals($desiredOrder, $newOrder); $this->assertEquals($desiredOrder, $newOrder);
} }
/** /**
* @covers GridFieldOrderableRows::getSortTable * @covers GridFieldOrderableRows::getSortTable
*/ */
public function testGetSortTable() { public function testGetSortTable()
{
$orderable = new GridFieldOrderableRows(); $orderable = new GridFieldOrderableRows();
$parent = new GridFieldOrderableRowsTest_Parent(); $parent = new GridFieldOrderableRowsTest_Parent();
@ -92,14 +94,14 @@ class GridFieldOrderableRowsTest extends SapphireTest {
$orderable->setSortField('ManyManySort')->getSortTable($parent->MyManyMany()) $orderable->setSortField('ManyManySort')->getSortTable($parent->MyManyMany())
); );
} }
} }
/**#@+ /**#@+
* @ignore * @ignore
*/ */
class GridFieldOrderableRowsTest_Parent extends DataObject implements TestOnly { class GridFieldOrderableRowsTest_Parent extends DataObject implements TestOnly
{
private static $has_many = array( private static $has_many = array(
'MyHasMany' => 'GridFieldOrderableRowsTest_Ordered', 'MyHasMany' => 'GridFieldOrderableRowsTest_Ordered',
@ -113,10 +115,10 @@ class GridFieldOrderableRowsTest_Parent extends DataObject implements TestOnly {
private static $many_many_extraFields = array( private static $many_many_extraFields = array(
'MyManyMany' => array('ManyManySort' => 'Int') 'MyManyMany' => array('ManyManySort' => 'Int')
); );
} }
class GridFieldOrderableRowsTest_Ordered extends DataObject implements TestOnly { class GridFieldOrderableRowsTest_Ordered extends DataObject implements TestOnly
{
private static $db = array( private static $db = array(
'Sort' => 'Int' 'Sort' => 'Int'
@ -129,10 +131,10 @@ class GridFieldOrderableRowsTest_Ordered extends DataObject implements TestOnly
private static $belongs_many_many =array( private static $belongs_many_many =array(
'MyManyMany' => 'GridFieldOrderableRowsTest_Parent', 'MyManyMany' => 'GridFieldOrderableRowsTest_Parent',
); );
} }
class GridFieldOrderableRowsTest_Subclass extends GridFieldOrderableRowsTest_Ordered implements TestOnly { class GridFieldOrderableRowsTest_Subclass extends GridFieldOrderableRowsTest_Ordered implements TestOnly
{
} }
/**#@-*/ /**#@-*/

View File

@ -1,16 +1,10 @@
GridFieldOrderableRowsTest_Ordered: GridFieldOrderableRowsTest_Ordered:
item1: item1:
Sort: 0
item2: item2:
Sort: 0
item3: item3:
Sort: 0
item4: item4:
Sort: 0
item5: item5:
Sort: 0
item6: item6:
Sort: 0
GridFieldOrderableRowsTest_Parent: GridFieldOrderableRowsTest_Parent:
parent: parent:
MyManyMany: MyManyMany: