SS4 Compliance & Updated Tests

This commit is contained in:
Reece 2017-05-27 14:46:40 +10:00
parent 37b3d86d60
commit 8b80547144
7 changed files with 1604 additions and 1307 deletions

View File

@ -1,681 +1,766 @@
<?php <?php
namespace UndefinedOffset\SortableGridField\Forms;
use SilverStripe\Admin\ModelAdmin;
use SilverStripe\Control\Controller;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Extensible;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridField_ActionProvider;
use SilverStripe\Forms\GridField\GridField_DataManipulator;
use SilverStripe\Forms\GridField\GridField_FormAction;
use SilverStripe\Forms\GridField\GridField_HTMLProvider;
use SilverStripe\Forms\GridField\GridFieldFilterHeader;
use SilverStripe\Forms\GridField\GridFieldPaginator;
use SilverStripe\Forms\GridField\GridFieldSortableHeader;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataQuery;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\ManyManyList;
use SilverStripe\ORM\RelationList;
use SilverStripe\ORM\SS_List;
use SilverStripe\ORM\UnsavedRelationList;
use SilverStripe\ORM\ValidationException;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\arrayData;
use SilverStripe\View\Requirements;
/** /**
* This component provides a checkbox which when checked enables drag-and-drop re-ordering of elements displayed in a {@link GridField} * This component provides a checkbox which when checked enables drag-and-drop re-ordering of elements displayed in a {@link GridField}
* *
* @package forms * @package forms
*/ */
class GridFieldSortableRows implements GridField_HTMLProvider, GridField_ActionProvider, GridField_DataManipulator { class GridFieldSortableRows implements GridField_HTMLProvider, GridField_ActionProvider, GridField_DataManipulator
protected $sortColumn; {
protected $disable_selection=true; /** @var string */
protected $append_to_top=false; protected $sortColumn;
protected $update_versioned_stage=null;
protected $custom_relation_name=null; /** @var bool */
protected $disable_selection = true;
/**
* @param string $sortColumn Column that should be used to update the sort information /** @var bool */
* @param bool $disableSelection Disable selection on the GridField when dragging protected $append_to_top = false;
* @param string $updateVersionStage Name of the versioned stage to update this disabled by default unless this is set
* @param string $customRelationName Name of the relationship to use, if left null the name is determined from the GridField's name /** @var null|string */
*/ protected $update_versioned_stage = null;
public function __construct($sortColumn, $disableSelection = true, $updateVersionStage = null, $customRelationName = null) {
$this->sortColumn = $sortColumn; /** @var null|string */
$this->disable_selection = $disableSelection; protected $custom_relation_name = null;
$this->update_versioned_stage = $updateVersionStage;
$this->custom_relation_name = $customRelationName; /** @var array */
} protected $tableMap = [];
/** /**
* Returns a map where the keys are fragment names and the values are pieces of HTML to add to these fragments. * @param string $sortColumn Column that should be used to update the sort information
* @param GridField $gridField Grid Field Reference * @param bool $disableSelection Disable selection on the GridField when dragging
* @return Array Map where the keys are fragment names and the values are pieces of HTML to add to these fragments. * @param string $updateVersionStage Name of the versioned stage to update this disabled by default unless this is set
*/ * @param string $customRelationName Name of the relationship to use, if left null the name is determined from the GridField's name
public function getHTMLFragments($gridField) { */
$dataList = $gridField->getList(); public function __construct($sortColumn, $disableSelection = true, $updateVersionStage = null, $customRelationName = null)
{
if(class_exists('UnsavedRelationList') && $dataList instanceof UnsavedRelationList) { $this->sortColumn = $sortColumn;
return array(); $this->disable_selection = $disableSelection;
} $this->update_versioned_stage = $updateVersionStage;
$this->custom_relation_name = $customRelationName;
$state = $gridField->State->GridFieldSortableRows; }
if(!is_bool($state->sortableToggle)) {
$state->sortableToggle = false; /**
} * Returns a map where the keys are fragment names and the values are pieces of HTML to add to these fragments.
* @param GridField $gridField Grid Field Reference
//Ensure user can edit * @return array Map where the keys are fragment names and the values are pieces of HTML to add to these fragments.
if(!singleton($gridField->getModelClass())->canEdit()){ */
return array(); public function getHTMLFragments($gridField)
} {
$dataList = $gridField->getList();
//Sort order toggle if (class_exists('UnsavedRelationList') && $dataList instanceof UnsavedRelationList) {
$sortOrderToggle = GridField_FormAction::create( return array();
$gridField, }
'sortablerows-toggle',
'sorttoggle', $state = $gridField->State->GridFieldSortableRows;
'sortableRowsToggle', if (!is_bool($state->sortableToggle)) {
null $state->sortableToggle = false;
)->addExtraClass('sortablerows-toggle'); }
//Ensure user can edit
$sortOrderSave = GridField_FormAction::create( if (!singleton($gridField->getModelClass())->canEdit()) {
$gridField, return array();
'sortablerows-savesort', }
'savesort',
'saveGridRowSort',
null //Sort order toggle
)->addExtraClass('sortablerows-savesort'); $sortOrderToggle = GridField_FormAction::create(
$gridField,
'sortablerows-toggle',
//Sort to Page Action 'sorttoggle',
$sortToPage = GridField_FormAction::create( 'sortableRowsToggle',
$gridField, null
'sortablerows-sorttopage', )->addExtraClass('sortablerows-toggle');
'sorttopage',
'sortToPage',
null $sortOrderSave = GridField_FormAction::create(
)->addExtraClass('sortablerows-sorttopage'); $gridField,
'sortablerows-savesort',
'savesort',
$data = array('SortableToggle' => $sortOrderToggle, 'saveGridRowSort',
'SortOrderSave' => $sortOrderSave, null
'SortToPage' => $sortToPage, )->addExtraClass('sortablerows-savesort');
'Checked' => ($state->sortableToggle == true ? ' checked = "checked"':''),
'List' => $dataList);
//Sort to Page Action
$forTemplate = new ArrayData($data); $sortToPage = GridField_FormAction::create(
$gridField,
'sortablerows-sorttopage',
//Inject Requirements 'sorttopage',
$custom = Config::inst()->get('GridFieldSortableRows', 'Base'); 'sortToPage',
$base = $custom ?: SORTABLE_GRIDFIELD_BASE; null
)->addExtraClass('sortablerows-sorttopage');
Requirements::css($base . '/css/GridFieldSortableRows.css');
Requirements::javascript($base . '/javascript/GridFieldSortableRows.js');
$data = array('SortableToggle' => $sortOrderToggle,
'SortOrderSave' => $sortOrderSave,
$args = array('Colspan' => count($gridField->getColumns()), 'ID' => $gridField->ID(), 'DisableSelection' => $this->disable_selection); 'SortToPage' => $sortToPage,
'Checked' => ($state->sortableToggle == true ? ' checked = "checked"' : ''),
'List' => $dataList);
$fragments=array('header' => $forTemplate->renderWith('GridFieldSortableRows', $args));
$forTemplate = new arrayData($data);
if($gridField->getConfig()->getComponentByType('GridFieldPaginator')) {
$fragments['after']=$forTemplate->renderWith('GridFieldSortableRows_paginator'); //Inject Requirements
} $custom = Config::inst()->get(GridFieldSortableRows::class, 'Base');
$base = $custom ?: SORTABLE_GRIDFIELD_BASE;
return $fragments;
} Requirements::css($base . '/css/GridFieldSortableRows.css');
Requirements::javascript($base . '/javascript/GridFieldSortableRows.js');
/**
* Manipulate the datalist as needed by this grid modifier. $args = array('Colspan' => count($gridField->getColumns()), 'ID' => $gridField->ID(), 'DisableSelection' => $this->disable_selection);
* @param GridField $gridField Grid Field Reference
* @param SS_List $dataList Data List to adjust $fragments = array('header' => $forTemplate->renderWith('SortableGridField\Forms\Includes\GridFieldSortableRows', $args));
* @return DataList Modified Data List
*/ if ($gridField->getConfig()->getComponentByType(GridFieldPaginator::class)) {
public function getManipulatedData(GridField $gridField, SS_List $dataList) { $fragments['after'] = $forTemplate->renderWith('SortableGridField\Forms\Includes\GridFieldSortableRows_paginator');
//Detect and correct items with a sort column value of 0 (push to bottom) }
$this->fixSortColumn($gridField, $dataList);
return $fragments;
}
$headerState = $gridField->State->GridFieldSortableHeader;
$state = $gridField->State->GridFieldSortableRows; /**
if ((!is_bool($state->sortableToggle) || $state->sortableToggle===false) && $headerState && is_string($headerState->SortColumn) && is_string($headerState->SortDirection)) { * Manipulate the datalist as needed by this grid modifier.
return $dataList->sort($headerState->SortColumn, $headerState->SortDirection); * @param GridField $gridField Grid Field Reference
} * @param SS_List|DataList $dataList Data List to adjust
* @return DataList Modified Data List
if ($state->sortableToggle === true) { */
$gridField->getConfig()->removeComponentsByType('GridFieldFilterHeader'); public function getManipulatedData(GridField $gridField, SS_List $dataList)
$gridField->getConfig()->removeComponentsByType('GridFieldSortableHeader'); {
} //Detect and correct items with a sort column value of 0 (push to bottom)
$this->fixSortColumn($gridField, $dataList);
return $dataList->sort($this->sortColumn);
}
$headerState = $gridField->State->GridFieldSortableHeader;
/** $state = $gridField->State->GridFieldSortableRows;
* Sets if new records should be appended to the top or the bottom of the list if ((!is_bool($state->sortableToggle) || $state->sortableToggle === false) && $headerState && is_string($headerState->SortColumn) && is_string($headerState->SortDirection)) {
* @param bool $value Boolean true to append to the top false to append to the bottom return $dataList->sort($headerState->SortColumn, $headerState->SortDirection);
* @return GridFieldSortableRows Returns the current instance }
*/
public function setAppendToTop($value) { if ($state->sortableToggle === true) {
$this->append_to_top=$value; $gridField->getConfig()->removeComponentsByType(GridFieldFilterHeader::class);
return $this; $gridField->getConfig()->removeComponentsByType(GridFieldSortableHeader::class);
} }
/** return $dataList->sort($this->sortColumn);
* @param bool $value Boolean true to disable selection of table contents false to enable selection }
* @return GridFieldSortableRows Returns the current instance
*/ /**
public function setDisableSelection($value){ * Sets if new records should be appended to the top or the bottom of the list
$this->disable_selection = $value; * @param bool $value Boolean true to append to the top false to append to the bottom
return $this; * @return GridFieldSortableRows Returns the current instance
} */
public function setAppendToTop($value)
/** {
* Sets the suffix of the versioned stage that should be updated along side the default stage $this->append_to_top = $value;
* @param string $value Versioned Stage to update this is disabled by default unless this is set return $this;
* @return GridFieldSortableRows Returns the current instance }
*/
public function setUpdateVersionedStage($value) { /**
$this->update_versioned_stage=$value; * @param bool $value Boolean true to disable selection of table contents false to enable selection
return $this; * @return GridFieldSortableRows Returns the current instance
} */
public function setDisableSelection($value)
/** {
* Sets the name of the relationship to use, by default the name is determined from the GridField's name $this->disable_selection = $value;
* @param string $value Name of the relationship to use, by default the name is determined from the GridField's name return $this;
* @return GridFieldSortableRows Returns the current instance }
*/
public function setCustomRelationName($value) { /**
$this->custom_relation_name=$value; * Sets the suffix of the versioned stage that should be updated along side the default stage
return $this; * @param string $value Versioned Stage to update this is disabled by default unless this is set
} * @return GridFieldSortableRows Returns the current instance
*/
/** public function setUpdateVersionedStage($value)
* Detects and corrects items with a sort column value of 0, by appending them to the bottom of the list {
* @param GridField $gridField Grid Field Reference $this->update_versioned_stage = $value;
* @param SS_List $dataList Data List of items to be checked return $this;
*/ }
protected function fixSortColumn($gridField, SS_List $dataList) {
if(class_exists('UnsavedRelationList') && $dataList instanceof UnsavedRelationList) { /**
return; * Sets the name of the relationship to use, by default the name is determined from the GridField's name
} * @param string $value Name of the relationship to use, by default the name is determined from the GridField's name
* @return GridFieldSortableRows Returns the current instance
$list=clone $dataList; */
$list=$list->alterDataQuery(function($query, SS_List $tmplist) { public function setCustomRelationName($value)
$query->limit(array()); {
return $query; $this->custom_relation_name = $value;
}); return $this;
}
$many_many = ($list instanceof ManyManyList);
if (!$many_many) { /**
$sng=singleton($gridField->getModelClass()); * Detects and corrects items with a sort column value of 0, by appending them to the bottom of the list
$fieldType=$sng->db($this->sortColumn); * @param GridField $gridField Grid Field Reference
if(!$fieldType || !(strtolower($fieldType) == 'int' || is_subclass_of($fieldType, 'Int'))) { * @param SS_List|DataList $dataList Data List of items to be checked
if(is_array($fieldType)) { */
user_error('Sort column '.$this->sortColumn.' could not be found in '.$gridField->getModelClass().'\'s ancestry', E_USER_ERROR); protected function fixSortColumn($gridField, SS_List $dataList)
}else { {
user_error('Sort column '.$this->sortColumn.' must be an Int, column is of type '.$fieldType, E_USER_ERROR); if ($dataList instanceof UnsavedRelationList) {
} return;
}
exit;
} /** @var SS_List|DataList $list */
} $list = clone $dataList;
$list = $list->alterDataQuery(function ($query, SS_List $tmplist) {
/** @var DataQuery $query */
$max = $list->Max($this->sortColumn); $query->limit(array());
$list=$list->filter($this->sortColumn, 0)->sort("Created,ID"); return $query;
if($list->Count()>0) { });
$owner = $gridField->Form->getRecord();
$sortColumn = $this->sortColumn; $many_many = ($list instanceof ManyManyList);
$i = 1; if (!$many_many) {
$sng = singleton($gridField->getModelClass());
if ($many_many) { $fieldType = $sng->config()->db[$this->sortColumn];
list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name:$gridField->getName()));
$extraFields=$owner->many_many_extraFields((!empty($this->custom_relation_name) ? $this->custom_relation_name:$gridField->getName())); if (!$fieldType || !(strtolower($fieldType) == 'int' || is_subclass_of($fieldType, 'Int'))) {
if (is_array($fieldType)) {
if(!$extraFields || !array_key_exists($this->sortColumn, $extraFields) || !($extraFields[$this->sortColumn]=='Int' || is_subclass_of('Int', $extraFields[$this->sortColumn]))) { user_error('Sort column ' . $this->sortColumn . ' could not be found in ' . $gridField->getModelClass() . '\'s ancestry', E_USER_ERROR);
user_error('Sort column '.$this->sortColumn.' must be an Int, column is of type '.$extraFields[$this->sortColumn], E_USER_ERROR); } else {
exit; user_error('Sort column ' . $this->sortColumn . ' must be an Int, column is of type ' . $fieldType, E_USER_ERROR);
} }
}else {
//Find table containing the sort column exit;
$table=false; }
$class=$gridField->getModelClass(); }
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED); $max = $list->Max($this->sortColumn);
if(!empty($db) && array_key_exists($sortColumn, $db)) { $list = $list->filter($this->sortColumn, 0)->sort("Created,ID");
$table=$class; if ($list->Count() > 0) {
}else { $owner = $gridField->getForm()->getRecord();
$classes=ClassInfo::ancestry($class, true); $sortColumn = $this->sortColumn;
foreach($classes as $class) { $i = 1;
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
if(!empty($db) && array_key_exists($sortColumn, $db)) { if ($many_many) {
$table=$class; list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name : $gridField->getName()));
break;
} /** @var DataObject $table */
} $table = $this->mapTableNameAndReturn($table);
}
$extraFields = $owner->many_many_extraFields((!empty($this->custom_relation_name) ? $this->custom_relation_name : $gridField->getName()));
if($table===false) {
user_error('Sort column '.$this->sortColumn.' could not be found in '.$gridField->getModelClass().'\'s ancestry', E_USER_ERROR); if (!$extraFields || !array_key_exists($this->sortColumn, $extraFields) || !($extraFields[$this->sortColumn] == 'Int' || is_subclass_of('Int', $extraFields[$this->sortColumn]))) {
exit; user_error('Sort column ' . $this->sortColumn . ' must be an Int, column is of type ' . $extraFields[$this->sortColumn], E_USER_ERROR);
} exit;
}
$baseDataClass=ClassInfo::baseDataClass($gridField->getModelClass()); } else {
} //Find table containing the sort column
$table = false;
$class = $gridField->getModelClass();
//Start transaction if supported
if(DB::getConn()->supportsTransactions()) { $db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
DB::getConn()->transactionStart(); if (!empty($db) && array_key_exists($sortColumn, $db)) {
} $table = $this->mapTableNameAndReturn($class);
} else {
$idCondition=null; $classes = ClassInfo::ancestry($class, true);
if($this->append_to_top && !($list instanceof RelationList)) { foreach ($classes as $class) {
$idCondition='"ID" IN(\''.implode("','", $dataList->getIDList()).'\')'; $db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
} if (!empty($db) && array_key_exists($sortColumn, $db)) {
$table = $this->mapTableNameAndReturn($class);
if($this->append_to_top) { break;
$topIncremented=array(); }
} }
}
foreach($list as $obj) {
if($many_many) { if ($table === false) {
if($this->append_to_top) { user_error('Sort column ' . $this->sortColumn . ' could not be found in ' . $gridField->getModelClass() . '\'s ancestry', E_USER_ERROR);
//Upgrade all the records (including the last inserted from 0 to 1) exit;
DB::query('UPDATE "' . $table }
. '" SET "' . $sortColumn . '" = "' . $sortColumn .'"+1'
. ' WHERE "' . $parentField . '" = ' . $owner->ID . (!empty($topIncremented) ? ' AND "' . $componentField . '" NOT IN(\''.implode('\',\'', $topIncremented).'\')':'')); $baseDataClass = DataObject::getSchema()->baseDataClass($gridField->getModelClass());
$baseDataClass = $this->mapTableNameAndReturn($baseDataClass);
$topIncremented[]=$obj->ID;
}else { }
//Append the last record to the bottom
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn .'" = ' . ($max + $i) //Start transaction if supported
. ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID); if (DB::get_conn()->supportsTransactions()) {
} DB::get_conn()->transactionStart();
}else if($this->append_to_top) { }
//Upgrade all the records (including the last inserted from 0 to 1)
DB::query('UPDATE "' . $table $idCondition = null;
. '" SET "' . $sortColumn . '" = "' . $sortColumn .'"+1' if ($this->append_to_top && !($list instanceof RelationList)) {
. ' WHERE '.($list instanceof RelationList ? '"' . $list->foreignKey . '" = '. $owner->ID:$idCondition) . (!empty($topIncremented) ? ' AND "ID" NOT IN(\''.implode('\',\'', $topIncremented).'\')':'')); $idCondition = '"ID" IN(\'' . implode("','", $dataList->getIDList()) . '\')';
}
if($this->update_versioned_stage && class_exists($table) && Object::has_extension($table, 'Versioned')) {
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage if ($this->append_to_top) {
. '" SET "' . $sortColumn . '" = "' . $sortColumn .'"+1' $topIncremented = array();
. ' WHERE '. ($list instanceof RelationList ? '"' . $list->foreignKey . '" = '. $owner->ID:$idCondition) . (!empty($topIncremented) ? ' AND "ID" NOT IN(\''.implode('\',\'', $topIncremented).'\')':'')); }
}
foreach ($list as $obj) {
$topIncremented[]=$obj->ID; if ($many_many) {
}else { if ($this->append_to_top) {
//Append the last record to the bottom //Upgrade all the records (including the last inserted from 0 to 1)
DB::query('UPDATE "' . $table DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = ' . ($max + $i) . '" SET "' . $sortColumn . '" = "' . $sortColumn . '"+1'
. ' WHERE "ID" = '. $obj->ID); . ' WHERE "' . $parentField . '" = ' . $owner->ID . (!empty($topIncremented) ? ' AND "' . $componentField . '" NOT IN(\'' . implode('\',\'', $topIncremented) . '\')' : ''));
//LastEdited
DB::query('UPDATE "' . $baseDataClass $topIncremented[] = $obj->ID;
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\'' } else {
. ' WHERE "ID" = '. $obj->ID); //Append the last record to the bottom
DB::query('UPDATE "' . $table
if($this->update_versioned_stage && class_exists($table) && Object::has_extension($table, 'Versioned')) { . '" SET "' . $sortColumn . '" = ' . ($max + $i)
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage . ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
. '" SET "' . $sortColumn . '" = ' . ($max + $i) }
. ' WHERE "ID" = '. $obj->ID); } else if ($this->append_to_top) {
//Upgrade all the records (including the last inserted from 0 to 1)
if(Object::has_extension($baseDataClass, 'Versioned')) { DB::query('UPDATE "' . $table
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage . '" SET "' . $sortColumn . '" = "' . $sortColumn . '"+1'
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\'' . ' WHERE ' . ($list instanceof RelationList ? '"' . $list->foreignKey . '" = ' . $owner->ID : $idCondition) . (!empty($topIncremented) ? ' AND "ID" NOT IN(\'' . implode('\',\'', $topIncremented) . '\')' : ''));
. ' WHERE "ID" = '. $obj->ID);
} if ($this->update_versioned_stage && class_exists($this->tableMap[$table]) && $this->hasVersionedExtension($this->tableMap[$table])) {
} DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
} . '" SET "' . $sortColumn . '" = "' . $sortColumn . '"+1'
. ' WHERE ' . ($list instanceof RelationList ? '"' . $list->foreignKey . '" = ' . $owner->ID : $idCondition) . (!empty($topIncremented) ? ' AND "ID" NOT IN(\'' . implode('\',\'', $topIncremented) . '\')' : ''));
$i++; }
}
$topIncremented[] = $obj->ID;
//Update LastEdited for affected records when using append to top on a many_many relationship } else {
if(!$many_many && $this->append_to_top && count($topIncremented)>0) { //Append the last record to the bottom
DB::query('UPDATE "' . $baseDataClass DB::query('UPDATE "' . $table
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\'' . '" SET "' . $sortColumn . '" = ' . ($max + $i)
. ' WHERE "ID" IN(\''.implode('\',\'', $topIncremented).'\')'); . ' WHERE "ID" = ' . $obj->ID);
//LastEdited
if($this->update_versioned_stage && class_exists($table) && Object::has_extension($table, 'Versioned') && Object::has_extension($baseDataClass, 'Versioned')) { DB::query('UPDATE "' . $baseDataClass
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage . '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\'' . ' WHERE "ID" = ' . $obj->ID);
. ' WHERE "ID" IN(\''.implode('\',\'', $topIncremented).'\')');
} if ($this->update_versioned_stage && class_exists($this->tableMap[$table]) && $this->hasVersionedExtension($this->tableMap[$table])) {
} DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
. '" SET "' . $sortColumn . '" = ' . ($max + $i)
. ' WHERE "ID" = ' . $obj->ID);
//End transaction if supported
if(DB::getConn()->supportsTransactions()) { if ($this->hasVersionedExtension($this->tableMap[$baseDataClass])) {
DB::getConn()->transactionEnd(); DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage
} . '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
} . ' WHERE "ID" = ' . $obj->ID);
} }
}
/** }
* Return a list of the actions handled by this action provider.
* @param GridField $gridField Grid Field Reference $i++;
* @return Array Array with action identifier strings. }
*/
public function getActions($gridField) { //Update LastEdited for affected records when using append to top on a many_many relationship
return array('saveGridRowSort', 'sortableRowsToggle', 'sortToPage'); if (!$many_many && $this->append_to_top && count($topIncremented) > 0) {
} DB::query('UPDATE "' . $baseDataClass
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
/** . ' WHERE "ID" IN(\'' . implode('\',\'', $topIncremented) . '\')');
* Handle an action on the given grid field.
* @param GridField $gridField Grid Field Reference if ($this->update_versioned_stage && class_exists($this->tableMap[$table]) && $this->hasVersionedExtension($this->tableMap[$table]) && $this->hasVersionedExtension($this->tableMap[$baseDataClass])) {
* @param String $actionName Action identifier, see {@link getActions()}. DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage
* @param Array $arguments Arguments relevant for this . '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
* @param Array $data All form data . ' WHERE "ID" IN(\'' . implode('\',\'', $topIncremented) . '\')');
*/ }
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { }
$state = $gridField->State->GridFieldSortableRows;
if (!is_bool($state->sortableToggle)) {
$state->sortableToggle = false; //End transaction if supported
} else if ($state->sortableToggle == true) { if (DB::get_conn()->supportsTransactions()) {
$gridField->getConfig()->removeComponentsByType('GridFieldFilterHeader'); DB::get_conn()->transactionEnd();
$gridField->getConfig()->removeComponentsByType('GridFieldSortableHeader'); }
} }
}
if ($actionName == 'savegridrowsort') { /**
return $this->saveGridRowSort($gridField, $data); * Return a list of the actions handled by this action provider.
} else if ($actionName == 'sorttopage') { * @param GridField $gridField Grid Field Reference
return $this->sortToPage($gridField, $data); * @return array array with action identifier strings.
} */
} public function getActions($gridField)
{
/** return array('saveGridRowSort', 'sortableRowsToggle', 'sortToPage');
* Handles saving of the row sort order }
* @param GridField $gridField Grid Field Reference
* @param Array $data Data submitted in the request /**
*/ * Handle an action on the given grid field.
protected function saveGridRowSort(GridField $gridField, $data) { * @param GridField $gridField Grid Field Reference
$dataList = $gridField->getList(); * @param String $actionName Action identifier, see {@link getActions()}.
* @param array $arguments Arguments relevant for this
if(class_exists('UnsavedRelationList') && $dataList instanceof UnsavedRelationList) { * @param array $data All form data
user_error('Cannot sort an UnsavedRelationList', E_USER_ERROR); */
return; public function handleAction(GridField $gridField, $actionName, $arguments, $data)
} {
$state = $gridField->State->GridFieldSortableRows;
if(!singleton($gridField->getModelClass())->canEdit()){ if (!is_bool($state->sortableToggle)) {
throw new ValidationException(_t('GridFieldSortableRows.EditPermissionsFailure', "No edit permissions"),0); $state->sortableToggle = false;
} } else if ($state->sortableToggle == true) {
$gridField->getConfig()->removeComponentsByType(GridFieldFilterHeader::class);
if (empty($data['ItemIDs'])) { $gridField->getConfig()->removeComponentsByType(GridFieldSortableHeader::class);
user_error('No items to sort', E_USER_ERROR); }
}
$className = $gridField->getModelClass(); if ($actionName == 'savegridrowsort') {
$owner = $gridField->Form->getRecord(); return $this->saveGridRowSort($gridField, $data);
$items = clone $gridField->getList(); } else if ($actionName == 'sorttopage') {
$many_many = ($items instanceof ManyManyList); return $this->sortToPage($gridField, $data);
$sortColumn = $this->sortColumn; }
$pageOffset = 0; }
if ($paginator = $gridField->getConfig()->getComponentsByType('GridFieldPaginator')->First()) { /**
$pageState = $gridField->State->GridFieldPaginator; * Handles saving of the row sort order
* @param GridField $gridField Grid Field Reference
if($pageState->currentPage && is_int($pageState->currentPage) && $pageState->currentPage>1) { * @param array $data Data submitted in the request
$pageOffset = $paginator->getItemsPerPage() * ($pageState->currentPage - 1); * @throws ValidationException If user has no edit permissions
} */
} protected function saveGridRowSort(GridField $gridField, $data)
{
$dataList = $gridField->getList();
if ($many_many) {
list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name:$gridField->getName())); if ($dataList instanceof UnsavedRelationList) {
}else { user_error('Cannot sort an UnsavedRelationList', E_USER_ERROR);
//Find table containing the sort column return;
$table=false; }
$class=$gridField->getModelClass();
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED); if (!singleton($gridField->getModelClass())->canEdit()) {
if(!empty($db) && array_key_exists($sortColumn, $db)) { throw new ValidationException(_t('GridFieldSortableRows.EditPermissionsFailure', "No edit permissions"), 0);
$table=$class; }
}else {
$classes=ClassInfo::ancestry($class, true); if (empty($data['ItemIDs'])) {
foreach($classes as $class) { user_error('No items to sort', E_USER_ERROR);
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED); }
if(!empty($db) && array_key_exists($sortColumn, $db)) {
$table=$class; $className = $gridField->getModelClass();
break; $owner = $gridField->Form->getRecord();
} $items = clone $gridField->getList();
} $many_many = ($items instanceof ManyManyList);
} $sortColumn = $this->sortColumn;
$pageOffset = 0;
if($table===false) {
user_error('Sort column '.$this->sortColumn.' could not be found in '.$gridField->getModelClass().'\'s ancestry', E_USER_ERROR); if ($paginator = $gridField->getConfig()->getComponentsByType(GridFieldPaginator::class)->First()) {
exit; $pageState = $gridField->State->GridFieldPaginator;
}
if ($pageState->currentPage && is_int($pageState->currentPage) && $pageState->currentPage > 1) {
$baseDataClass=ClassInfo::baseDataClass($gridField->getModelClass()); $pageOffset = $paginator->getItemsPerPage() * ($pageState->currentPage - 1);
} }
}
//Event to notify the Controller or owner DataObject before list sort
if($owner && $owner instanceof DataObject && method_exists($owner, 'onBeforeGridFieldRowSort')) { if ($many_many) {
$owner->onBeforeGridFieldRowSort(clone $items); list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name : $gridField->getName()));
}else if(Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onBeforeGridFieldRowSort')) {
Controller::curr()->onBeforeGridFieldRowSort(clone $items); /** @var DataObject $table */
} $table = $this->mapTableNameAndReturn($table);
} else {
//Find table containing the sort column
//Start transaction if supported $table = false;
if(DB::getConn()->supportsTransactions()) { $class = $gridField->getModelClass();
DB::getConn()->transactionStart(); $db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
} if (!empty($db) && array_key_exists($sortColumn, $db)) {
$table = $this->mapTableNameAndReturn($class);
} else {
//Perform sorting $classes = ClassInfo::ancestry($class, true);
$ids = explode(',', $data['ItemIDs']); foreach ($classes as $class) {
for($sort = 0;$sort<count($ids);$sort++) { $db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
$id = intval($ids[$sort]); if (!empty($db) && array_key_exists($sortColumn, $db)) {
if ($many_many) { $table = $this->mapTableNameAndReturn($class);
DB::query('UPDATE "' . $table break;
. '" SET "' . $sortColumn.'" = ' . (($sort + 1) + $pageOffset) }
. ' WHERE "' . $componentField . '" = ' . $id . ' AND "' . $parentField . '" = ' . $owner->ID); }
} else { }
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = ' . (($sort + 1) + $pageOffset) if ($table === false) {
. ' WHERE "ID" = '. $id); user_error('Sort column ' . $this->sortColumn . ' could not be found in ' . $gridField->getModelClass() . '\'s ancestry', E_USER_ERROR);
exit;
DB::query('UPDATE "' . $baseDataClass }
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
. ' WHERE "ID" = '. $id); $baseDataClass = DataObject::getSchema()->baseDataClass($gridField->getModelClass());
$baseDataClass = $this->mapTableNameAndReturn($baseDataClass);
if($this->update_versioned_stage && class_exists($table) && Object::has_extension($table, 'Versioned')) { }
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
. '" SET "' . $sortColumn . '" = ' . (($sort + 1) + $pageOffset)
. ' WHERE "ID" = '. $id); //Event to notify the Controller or owner DataObject before list sort
if ($owner && $owner instanceof DataObject && method_exists($owner, 'onBeforeGridFieldRowSort')) {
if(Object::has_extension($baseDataClass, 'Versioned')) { $owner->onBeforeGridFieldRowSort(clone $items);
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage } else if (Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onBeforeGridFieldRowSort')) {
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\'' Controller::curr()->onBeforeGridFieldRowSort(clone $items);
. ' WHERE "ID" = '. $id); }
}
} //Start transaction if supported
} if (DB::get_conn()->supportsTransactions()) {
} DB::get_conn()->transactionStart();
}
//End transaction if supported //Perform sorting
if(DB::getConn()->supportsTransactions()) { $ids = explode(',', $data['ItemIDs']);
DB::getConn()->transactionEnd(); for ($sort = 0; $sort < count($ids); $sort++) {
} $id = intval($ids[$sort]);
if ($many_many) {
DB::query('UPDATE "' . $table
//Event to notify the Controller or owner DataObject after list sort . '" SET "' . $sortColumn . '" = ' . (($sort + 1) + $pageOffset)
if($owner && $owner instanceof DataObject && method_exists($owner, 'onAfterGridFieldRowSort')) { . ' WHERE "' . $componentField . '" = ' . $id . ' AND "' . $parentField . '" = ' . $owner->ID);
$owner->onAfterGridFieldRowSort(clone $items); } else {
}else if(Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onAfterGridFieldRowSort')) { DB::query('UPDATE "' . $table
Controller::curr()->onAfterGridFieldRowSort(clone $items); . '" SET "' . $sortColumn . '" = ' . (($sort + 1) + $pageOffset)
} . ' WHERE "ID" = ' . $id);
}
DB::query('UPDATE "' . $baseDataClass
/** . '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
* Handles sorting across pages . ' WHERE "ID" = ' . $id);
* @param GridField $gridField Grid Field Reference
* @param Array $data Data submitted in the request if ($this->update_versioned_stage && class_exists($this->tableMap[$table]) && $this->hasVersionedExtension($this->tableMap[$table])) {
*/ DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
protected function sortToPage(GridField $gridField, $data) { . '" SET "' . $sortColumn . '" = ' . (($sort + 1) + $pageOffset)
if (!$paginator = $gridField->getConfig()->getComponentsByType('GridFieldPaginator')->First()) { . ' WHERE "ID" = ' . $id);
user_error('Paginator not detected', E_USER_ERROR);
} if ($this->hasVersionedExtension($this->tableMap[$baseDataClass])) {
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage
if (empty($data['ItemID'])) { . '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
user_error('No item to sort', E_USER_ERROR); . ' WHERE "ID" = ' . $id);
} }
}
if (empty($data['Target'])) { }
user_error('No target page', E_USER_ERROR); }
}
//End transaction if supported
$className = $gridField->getModelClass(); if (DB::get_conn()->supportsTransactions()) {
$owner = $gridField->Form->getRecord(); DB::get_conn()->transactionEnd();
$items = clone $gridField->getList(); }
$many_many = ($items instanceof ManyManyList);
$sortColumn = $this->sortColumn;
$targetItem = $items->byID(intval($data['ItemID'])); //Event to notify the Controller or owner DataObject after list sort
if ($owner && $owner instanceof DataObject && method_exists($owner, 'onAfterGridFieldRowSort')) {
if (!$targetItem) { $owner->onAfterGridFieldRowSort(clone $items);
user_error('Target item not found', E_USER_ERROR); } else if (Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onAfterGridFieldRowSort')) {
} Controller::curr()->onAfterGridFieldRowSort(clone $items);
}
$currentPage = 1; }
/**
$pageState = $gridField->State->GridFieldPaginator; * Handles sorting across pages
if($pageState->currentPage && $pageState->currentPage>1) { * @param GridField $gridField Grid Field Reference
$currentPage = $pageState->currentPage; * @param array $data Data submitted in the request
} */
protected function sortToPage(GridField $gridField, $data)
{
if ($many_many) { if (!$paginator = $gridField->getConfig()->getComponentsByType(GridFieldPaginator::class)->First()) {
list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name:$gridField->getName())); user_error('Paginator not detected', E_USER_ERROR);
} }
if (empty($data['ItemID'])) {
if ($data['Target'] == 'previouspage') { user_error('No item to sort', E_USER_ERROR);
$items = $items->limit($paginator->getItemsPerPage() + 1, ($paginator->getItemsPerPage() * ($currentPage - 1)) - 1); }
} else if ($data['Target'] == 'nextpage') {
$items = $items->limit($paginator->getItemsPerPage() + 1, $paginator->getItemsPerPage() * ($currentPage - 1)); if (empty($data['Target'])) {
} else { user_error('No target page', E_USER_ERROR);
user_error('Not implemented: '.$data['Target'], E_USER_ERROR); }
}
/** @var Extensible $className */
$sortPositions = $items->column($sortColumn); $className = $gridField->getModelClass();
$owner = $gridField->Form->getRecord();
//Event to notify the Controller or owner DataObject before list sort /** @var DataList $items */
if($owner && $owner instanceof DataObject && method_exists($owner, 'onBeforeGridFieldPageSort')) { $items = clone $gridField->getList();
$owner->onBeforeGridFieldPageSort(clone $items);
}else if(Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onBeforeGridFieldPageSort')) { $many_many = ($items instanceof ManyManyList);
Controller::curr()->onBeforeGridFieldPageSort(clone $items); $sortColumn = $this->sortColumn;
} $targetItem = $items->byID(intval($data['ItemID']));
if (!$targetItem) {
//Find the sort column user_error('Target item not found', E_USER_ERROR);
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { }
$table=false;
$classes=ClassInfo::ancestry($className, true); $currentPage = 1;
foreach($classes as $class) {
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED); $pageState = $gridField->State->GridFieldPaginator;
if(!empty($db) && array_key_exists($sortColumn, $db)) { if ($pageState->currentPage && $pageState->currentPage > 1) {
$table=$class; $currentPage = $pageState->currentPage;
break; }
}
} if ($many_many) {
list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name : $gridField->getName()));
if($table===false) { $table = $this->mapTableNameAndReturn($table);
user_error('Sort column '.$this->sortColumn.' could not be found in '.$gridField->getModelClass().'\'s ancestry', E_USER_ERROR); }
exit;
} if ($data['Target'] == 'previouspage') {
} $items = $items->limit($paginator->getItemsPerPage() + 1, ($paginator->getItemsPerPage() * ($currentPage - 1)) - 1);
} else if ($data['Target'] == 'nextpage') {
$items = $items->limit($paginator->getItemsPerPage() + 1, $paginator->getItemsPerPage() * ($currentPage - 1));
//Start transaction if supported } else {
if(DB::getConn()->supportsTransactions()) { user_error('Not implemented: ' . $data['Target'], E_USER_ERROR);
DB::getConn()->transactionStart(); }
}
$sortPositions = $items->column($sortColumn);
if($data['Target']=='previouspage') {
if ($many_many) { //Event to notify the Controller or owner DataObject before list sort
DB::query('UPDATE "' . $table if ($owner && $owner instanceof DataObject && method_exists($owner, 'onBeforeGridFieldPageSort')) {
. '" SET "' . $sortColumn.'" = ' . $sortPositions[0] $owner->onBeforeGridFieldPageSort(clone $items);
. ' WHERE "' . $componentField . '" = ' . $targetItem->ID . ' AND "' . $parentField . '" = ' . $owner->ID); } else if (Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onBeforeGridFieldPageSort')) {
} else { Controller::curr()->onBeforeGridFieldPageSort(clone $items);
$targetItem->$sortColumn = $sortPositions[0]; }
$targetItem->write();
//Find the sort column
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { if ($this->update_versioned_stage && $this->hasVersionedExtension($className)) {
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage $table = false;
. '" SET "' . $sortColumn.'" = ' . $sortPositions[0] $classes = ClassInfo::ancestry($className, true);
. ' WHERE "ID" = ' . $targetItem->ID); foreach ($classes as $class) {
} $db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
} if (!empty($db) && array_key_exists($sortColumn, $db)) {
$table = $this->mapTableNameAndReturn($class);
break;
$i = 1; }
foreach ($items as $obj) { }
if ($obj->ID == $targetItem->ID) {
continue; if ($table === false) {
} user_error('Sort column ' . $this->sortColumn . ' could not be found in ' . $gridField->getModelClass() . '\'s ancestry', E_USER_ERROR);
exit;
}
if ($many_many) { }
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn.'" = ' . $sortPositions[$i] //Start transaction if supported
. ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID); if (DB::get_conn()->supportsTransactions()) {
} else { DB::get_conn()->transactionStart();
$obj->$sortColumn = $sortPositions[$i]; }
$obj->write();
if ($data['Target'] == 'previouspage') {
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { if ($many_many) {
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn.'" = ' . $sortPositions[$i] . '" SET "' . $sortColumn . '" = ' . $sortPositions[0]
. ' WHERE "ID" = ' . $obj->ID); . ' WHERE "' . $componentField . '" = ' . $targetItem->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
} } else {
} $targetItem->$sortColumn = $sortPositions[0];
$targetItem->write();
$i++;
} if ($this->update_versioned_stage && $this->hasVersionedExtension($className)) {
} else { DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
if ($many_many) { . '" SET "' . $sortColumn . '" = ' . $sortPositions[0]
DB::query('UPDATE "' . $table . ' WHERE "ID" = ' . $targetItem->ID);
. '" SET "' . $sortColumn.'" = ' . $sortPositions[count($sortPositions) - 1] }
. ' WHERE "' . $componentField . '" = ' . $targetItem->ID . ' AND "' . $parentField . '" = ' . $owner->ID); }
} else {
$targetItem->$sortColumn = $sortPositions[count($sortPositions) - 1]; $i = 1;
$targetItem->write(); foreach ($items as $obj) {
if ($obj->ID == $targetItem->ID) {
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { continue;
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage }
. '" SET "' . $sortColumn.'" = ' . $sortPositions[count($sortPositions) - 1]
. ' WHERE "ID" = ' . $targetItem->ID);
} if ($many_many) {
} DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = ' . $sortPositions[$i]
. ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
$i = 0; } else {
foreach ($items as $obj) { $obj->$sortColumn = $sortPositions[$i];
if ($obj->ID == $targetItem->ID) { $obj->write();
continue;
} if ($this->update_versioned_stage && $this->hasVersionedExtension($className)) {
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
. '" SET "' . $sortColumn . '" = ' . $sortPositions[$i]
if ($many_many) { . ' WHERE "ID" = ' . $obj->ID);
DB::query('UPDATE "' . $table }
. '" SET "' . $sortColumn.'" = ' . $sortPositions[$i] }
. ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
} else { $i++;
$obj->$sortColumn = $sortPositions[$i]; }
$obj->write(); } else {
if ($many_many) {
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { DB::query('UPDATE "' . $table
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage . '" SET "' . $sortColumn . '" = ' . $sortPositions[count($sortPositions) - 1]
. '" SET "' . $sortColumn.'" = ' . $sortPositions[$i] . ' WHERE "' . $componentField . '" = ' . $targetItem->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
. ' WHERE "ID" = ' . $obj->ID); } else {
} $targetItem->$sortColumn = $sortPositions[count($sortPositions) - 1];
} $targetItem->write();
$i++; if ($this->update_versioned_stage && $this->hasVersionedExtension($className)) {
} DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
} . '" SET "' . $sortColumn . '" = ' . $sortPositions[count($sortPositions) - 1]
. ' WHERE "ID" = ' . $targetItem->ID);
}
//End transaction if supported }
if(DB::getConn()->supportsTransactions()) {
DB::getConn()->transactionEnd(); $i = 0;
} foreach ($items as $obj) {
if ($obj->ID == $targetItem->ID) {
continue;
//Event to notify the Controller or owner DataObject after list sort }
if($owner && $owner instanceof DataObject && method_exists($owner, 'onAfterGridFieldPageSort')) {
$owner->onAfterGridFieldPageSort(clone $items);
}else if(Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onAfterGridFieldPageSort')) { if ($many_many) {
Controller::curr()->onAfterGridFieldPageSort(clone $items); DB::query('UPDATE "' . $table
} . '" SET "' . $sortColumn . '" = ' . $sortPositions[$i]
} . ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
} else {
$obj->$sortColumn = $sortPositions[$i];
$obj->write();
if ($this->update_versioned_stage && $this->hasVersionedExtension($className)) {
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
. '" SET "' . $sortColumn . '" = ' . $sortPositions[$i]
. ' WHERE "ID" = ' . $obj->ID);
}
}
$i++;
}
}
//End transaction if supported
if (DB::get_conn()->supportsTransactions()) {
DB::get_conn()->transactionEnd();
}
//Event to notify the Controller or owner DataObject after list sort
if ($owner && $owner instanceof DataObject && method_exists($owner, 'onAfterGridFieldPageSort')) {
$owner->onAfterGridFieldPageSort(clone $items);
} else if (Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onAfterGridFieldPageSort')) {
Controller::curr()->onAfterGridFieldPageSort(clone $items);
}
}
/**
* Check to see if the given class name has the Versioned extension
*
* @param Extensible|string $className
* @return bool
*/
public function hasVersionedExtension($className)
{
return $className::has_extension(Versioned::class);
}
/**
* Checks to see if $table_name is declared on the DataObject, if not returns string as given
*
* @param $tableName
* @return mixed
*/
public function mapTableNameAndReturn($tableName)
{
if (array_key_exists($tableName, $this->tableMap)) {
return $this->tableMap[$tableName];
}
$realName = (Config::inst()->get($tableName, 'table_name', CONFIG::UNINHERITED)) ? Config::inst()->get($tableName, 'table_name', CONFIG::UNINHERITED) : $table;
$this->tableMap[$realName] = $tableName;
return $realName;
}
} }
?>

View File

@ -1,253 +1,361 @@
<?php <?php
class GridFieldSortableRowsAutoSortTest extends SapphireTest {
/** @var string */
public static $fixture_file = 'GridFieldSortableRowsAutoSortTest.yml';
/** @var array */ namespace UndefinedOffset\SortableGridField\Tests;
protected $extraDataObjects = array(
'GridFieldAction_SortOrder_Player',
'GridFieldAction_SortOrder_VPlayer',
'GridFieldAction_SortOrder_TestParent',
'GridFieldAction_SortOrder_BaseObject',
'GridFieldAction_SortOrder_ChildObject'
);
public function testAutoSort() { use SilverStripe\Control\Controller;
if(Member::currentUser()) { Member::currentUser()->logOut(); } use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\Session;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Dev\TestOnly;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\Security\Member;
use SilverStripe\Versioned\Versioned;
use UndefinedOffset\SortableGridField\Forms\GridFieldSortableRows;
$list = GridFieldAction_SortOrder_Player::get(); /**
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder')); * Class GridFieldSortableRowsAutoSortTest
$gridField = new GridField('testfield', 'testfield', $list, $config); *
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList()); * @package SortableGridField\Tests
*/
class GridFieldSortableRowsAutoSortTest extends SapphireTest
{
/** @var string */
public static $fixture_file = 'sortablegridfield/tests/forms/GridFieldSortableRowsAutoSortTest.yml';
$stateID = 'testGridStateActionField'; /** @var array */
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortableRowsToggle', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); protected static $extra_dataobjects = array(
$request = new SS_HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $form->getSecurityToken()->getName()=>$form->getSecurityToken()->getValue())); GridFieldAction_SortOrder_Player::class,
$gridField->gridFieldAlterAction(array('StateID'=>$stateID), $form, $request); GridFieldAction_SortOrder_VPlayer::class,
GridFieldAction_SortOrder_TestParent::class,
GridFieldAction_SortOrder_BaseObject::class,
GridFieldAction_SortOrder_ChildObject::class
);
//Insure sort ran public function testAutoSort()
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run'); {
if (Member::currentUser()) {
Member::currentUser()->logOut();
}
$list = GridFieldAction_SortOrder_Player::get();
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
$gridField = new GridField('testfield', 'testfield', $list, $config);
$form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($gridField)), new FieldList());
$stateID = 'testGridStateActionField';
Session::set($stateID, array('grid' => '', 'actionName' => 'sortableRowsToggle', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
$request = new HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $form->getSecurityToken()->getName() => $form->getSecurityToken()->getValue()));
$gridField->gridFieldAlterAction(array('StateID' => $stateID), $form, $request);
//Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run');
//Check for duplicates (there shouldn't be any) //Check for duplicates (there shouldn't be any)
$count=$list->Count(); $count = $list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); $indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected'); $this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected');
} }
public function testAppendToTopAutoSort() { public function testAppendToTopAutoSort()
if(Member::currentUser()) { Member::currentUser()->logOut(); } {
if (Member::currentUser()) {
Member::currentUser()->logOut();
}
$list = GridFieldAction_SortOrder_Player::get(); $list = GridFieldAction_SortOrder_Player::get();
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder')); $config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
$gridField = new GridField('testfield', 'testfield', $list, $config); $gridField = new GridField('testfield', 'testfield', $list, $config);
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList()); $form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($gridField)), new FieldList());
$gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setAppendToTop(true); /** @var GridFieldSortableRows $sortableRows */
$sortableRows = $gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$sortableRows->setAppendToTop(true);
$this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not have run'); $this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not have run');
$stateID = 'testGridStateActionField'; $stateID = 'testGridStateActionField';
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortableRowsToggle', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); Session::set($stateID, array('grid' => '', 'actionName' => 'sortableRowsToggle', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
$request = new SS_HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $form->getSecurityToken()->getName()=>$form->getSecurityToken()->getValue())); $request = new HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $form->getSecurityToken()->getName() => $form->getSecurityToken()->getValue()));
$gridField->gridFieldAlterAction(array('StateID'=>$stateID), $form, $request); $gridField->gridFieldAlterAction(array('StateID' => $stateID), $form, $request);
//Insure sort ran //Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run'); $this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run');
//Check for duplicates (there shouldn't be any) //Check for duplicates (there shouldn't be any)
$count=$list->Count(); $count = $list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); $indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected'); $this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected');
} }
public function testAutoSortVersioned() { public function testAutoSortVersioned()
if(Member::currentUser()) { Member::currentUser()->logOut(); } {
if (Member::currentUser()) {
Member::currentUser()->logOut();
}
//Force versioned to reset //Force versioned to reset
Versioned::reset(); Versioned::reset();
$list = GridFieldAction_SortOrder_VPlayer::get(); $list = GridFieldAction_SortOrder_VPlayer::get();
//Publish all records //Publish all records
foreach($list as $item) { foreach ($list as $item) {
$item->publish('Stage', 'Live'); $item->publish('Stage', 'Live');
} }
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder', true, 'Live')); $config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder', true, 'Live'));
$gridField = new GridField('testfield', 'testfield', $list, $config); $gridField = new GridField('testfield', 'testfield', $list, $config);
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList()); $form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($gridField)), new FieldList());
$stateID = 'testGridStateActionField'; $stateID = 'testGridStateActionField';
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortableRowsToggle', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); Session::set($stateID, array('grid' => '', 'actionName' => 'sortableRowsToggle', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
$request = new SS_HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $form->getSecurityToken()->getName()=>$form->getSecurityToken()->getValue())); $request = new HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $form->getSecurityToken()->getName() => $form->getSecurityToken()->getValue()));
$gridField->gridFieldAlterAction(array('StateID'=>$stateID), $form, $request); $gridField->gridFieldAlterAction(array('StateID' => $stateID), $form, $request);
//Insure sort ran //Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Stage"'); $this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Stage"');
//Check for duplicates (there shouldn't be any) //Check for duplicates (there shouldn't be any)
$count=$list->Count(); $count = $list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); $indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected on Versioned stage "Stage"'); $this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected on Versioned stage "Stage"');
//Force versioned over to Live stage //Force versioned over to Live stage
Versioned::reading_stage('Live'); Versioned::set_reading_mode('Live');
//Get live instance //Get live instance
$obj=Versioned::get_one_by_stage('GridFieldAction_SortOrder_VPlayer', 'Live', '"ID"='.$list->last()->ID); $obj = Versioned::get_one_by_stage(GridFieldAction_SortOrder_VPlayer::class, 'Live', '"ID"=' . $list->last()->ID);
//Insure sort ran //Insure sort ran
$this->assertEquals(3, $obj->SortOrder, 'Auto sort should have run on Versioned stage "Live"'); $this->assertEquals(3, $obj->SortOrder, 'Auto sort should have run on Versioned stage "Live"');
//Check for duplicates (there shouldn't be any) //Check for duplicates (there shouldn't be any)
$list=Versioned::get_by_stage('GridFieldAction_SortOrder_VPlayer', 'Live'); $list = Versioned::get_by_stage(GridFieldAction_SortOrder_VPlayer::class, 'Live');
$count=$list->Count(); $count = $list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); $indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected on Versioned stage "Live"'); $this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected on Versioned stage "Live"');
} }
public function testAppendToTopAutoSortVersioned() { public function testAppendToTopAutoSortVersioned()
if(Member::currentUser()) { Member::currentUser()->logOut(); } {
if (Member::currentUser()) {
Member::currentUser()->logOut();
}
//Force versioned to reset //Force versioned to reset
Versioned::reset(); Versioned::reset();
$list = GridFieldAction_SortOrder_VPlayer::get(); $list = GridFieldAction_SortOrder_VPlayer::get();
//Publish all records //Publish all records
foreach($list as $item) { foreach ($list as $item) {
$item->publish('Stage', 'Live'); $item->publish('Stage', 'Live');
} }
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder', true, 'Live')); $config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder', true, 'Live'));
$gridField = new GridField('testfield', 'testfield', $list, $config); $gridField = new GridField('testfield', 'testfield', $list, $config);
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList()); $form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($gridField)), new FieldList());
$gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setAppendToTop(true); /** @var GridFieldSortableRows $sortableRows */
$sortableRows = $gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$sortableRows->setAppendToTop(true);
$this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not have run on Versioned stage "Stage"'); $this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not have run on Versioned stage "Stage"');
$stateID = 'testGridStateActionField'; $stateID = 'testGridStateActionField';
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortableRowsToggle', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); Session::set($stateID, array('grid' => '', 'actionName' => 'sortableRowsToggle', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
$request = new SS_HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $form->getSecurityToken()->getName()=>$form->getSecurityToken()->getValue())); $request = new HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $form->getSecurityToken()->getName() => $form->getSecurityToken()->getValue()));
$gridField->gridFieldAlterAction(array('StateID'=>$stateID), $form, $request); $gridField->gridFieldAlterAction(array('StateID' => $stateID), $form, $request);
//Insure sort ran //Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Stage"'); $this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Stage"');
//Check for duplicates (there shouldn't be any) //Check for duplicates (there shouldn't be any)
$count=$list->Count(); $count = $list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); $indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected on Versioned stage "Stage"'); $this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected on Versioned stage "Stage"');
//Force versioned over to Live stage //Force versioned over to Live stage
Versioned::reading_stage('Live'); Versioned::set_reading_mode('Live');
//Insure sort ran //Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Live"'); $this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Live"');
//Check for duplicates (there shouldn't be any) //Check for duplicates (there shouldn't be any)
$count=$list->Count(); $count = $list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); $indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected on Versioned stage "Live"'); $this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected on Versioned stage "Live"');
} }
public function testAppendToTopAutoSortChild() { public function testAppendToTopAutoSortChild()
if(Member::currentUser()) { Member::currentUser()->logOut(); } {
if (Member::currentUser()) {
Member::currentUser()->logOut();
}
//Push the edit date into the past, we're checking this later //Push the edit date into the past, we're checking this later
DB::query('UPDATE "GridFieldAction_SortOrder_BaseObject" SET "LastEdited"=\''.date('Y-m-d 00:00:00', strtotime('yesterday')).'\''); DB::query('UPDATE "GridFieldAction_SortOrder_BaseObject" SET "LastEdited"=\'' . date('Y-m-d 00:00:00', strtotime('yesterday')) . '\'');
$parent = GridFieldAction_SortOrder_TestParent::get()->first(); /** @var GridFieldAction_SortOrder_TestParent $parent */
$list = $parent->TestRelation(); $parent = GridFieldAction_SortOrder_TestParent::get()->first();
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
$gridField = new GridField('testfield', 'testfield', $list, $config);
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList());
$form->loadDataFrom($parent);
$gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setAppendToTop(true); /** @var DataList $list */
$list = $parent->TestRelation();
$this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not have run'); $config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
$gridField = new GridField('testfield', 'testfield', $list, $config);
$form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($gridField)), new FieldList());
$form->loadDataFrom($parent);
$stateID = 'testGridStateActionField'; /** @var GridFieldSortableRows $sortableRows */
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortableRowsToggle', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); $sortableRows = $gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$request = new SS_HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $form->getSecurityToken()->getName()=>$form->getSecurityToken()->getValue())); $sortableRows->setAppendToTop(true);
$gridField->gridFieldAlterAction(array('StateID'=>$stateID), $form, $request);
//Insure sort ran $this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not have run');
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run');
$stateID = 'testGridStateActionField';
Session::set($stateID, array('grid' => '', 'actionName' => 'sortableRowsToggle', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
$request = new HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $form->getSecurityToken()->getName() => $form->getSecurityToken()->getValue()));
$gridField->gridFieldAlterAction(array('StateID' => $stateID), $form, $request);
//Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run');
//Check for duplicates (there shouldn't be any) //Check for duplicates (there shouldn't be any)
$count=$list->Count(); $count = $list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); $indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected'); $this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected');
//Make sure the last edited is today for all records //Make sure the last edited is today for all records
$this->assertEquals(3, $list->filter('LastEdited:GreaterThan', date('Y-m-d 00:00:00'))->count()); $this->assertEquals(3, $list->filter('LastEdited:GreaterThan', date('Y-m-d 00:00:00'))->count());
} }
} }
class GridFieldAction_SortOrder_Player extends DataObject implements TestOnly { /**
static $db = array( * Class GridFieldAction_SortOrder_Player
'Name' => 'Varchar', *
'SortOrder' => 'Int' * @package SortableGridField\Tests
); * @property string Name
* @property int SortOrder
*/
class GridFieldAction_SortOrder_Player extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_Player';
static $default_sort='SortOrder'; private static $db = array(
'Name' => 'Varchar',
'SortOrder' => 'Int'
);
private static $default_sort = 'SortOrder';
} }
class GridFieldAction_SortOrder_VPlayer extends DataObject implements TestOnly { /**
static $db = array( * Class GridFieldAction_SortOrder_VPlayer
'Name' => 'Varchar', *
'SortOrder' => 'Int' * @package SortableGridField\Tests
); * @property string Name
* @property int SortOrder
*/
class GridFieldAction_SortOrder_VPlayer extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_VPlayer';
static $default_sort = 'SortOrder'; private static $db = array(
'Name' => 'Varchar',
'SortOrder' => 'Int'
);
static $extensions=array( private static $default_sort = 'SortOrder';
"Versioned('Stage', 'Live')"
); private static $extensions = array(
"SilverStripe\\Versioned\\Versioned('Stage', 'Live')"
);
} }
class GridFieldAction_SortOrder_TestParent extends DataObject implements TestOnly { /**
static $db = array( * Class GridFieldAction_SortOrder_TestParent
'Name' => 'Varchar' *
); * @package SortableGridField\Tests
* @property string Name
* @method GridFieldAction_SortOrder_ChildObject TestRelation
*/
class GridFieldAction_SortOrder_TestParent extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_TestParent';
static $has_many = array( private static $db = array(
'TestRelation' => 'GridFieldAction_SortOrder_ChildObject' 'Name' => 'Varchar'
); );
private static $has_many = array(
'TestRelation' => GridFieldAction_SortOrder_ChildObject::class
);
} }
class GridFieldAction_SortOrder_BaseObject extends DataObject implements TestOnly { /**
static $db = array( * Class GridFieldAction_SortOrder_BaseObject
'Name' => 'Varchar' *
); * @package SortableGridField\Tests
* @property string Name
*/
class GridFieldAction_SortOrder_BaseObject extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_BaseObject';
private static $db = array(
'Name' => 'Varchar'
);
} }
class GridFieldAction_SortOrder_ChildObject extends GridFieldAction_SortOrder_BaseObject implements TestOnly { /**
static $db = array( * Class GridFieldAction_SortOrder_ChildObject
'SortOrder' => 'Int' *
); * @package SortableGridField\Tests
* @property int SortOrder
* @method GridFieldAction_SortOrder_TestParent Parent
*/
class GridFieldAction_SortOrder_ChildObject extends GridFieldAction_SortOrder_BaseObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_ChildObject';
static $has_one = array( private static $db = array(
'Parent'=>'GridFieldAction_SortOrder_TestParent' 'SortOrder' => 'Int'
); );
static $default_sort='SortOrder'; private static $has_one = array(
'Parent' => GridFieldAction_SortOrder_TestParent::class
);
private static $default_sort = 'SortOrder';
}
/**
* Class SortableGridField_DummyController
*
* @package SortableGridField\Tests
*/
class SortableGridField_DummyController extends Controller
{
private static $url_segment = 'sortable-grid-field';
} }
?>

View File

@ -1,39 +1,39 @@
GridFieldAction_SortOrder_Player: UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Player:
player1: player1:
Name: Player 1 Name: Player 1
SortOrder: 0 SortOrder: 0
player2: player2:
Name: Player 2 Name: Player 2
SortOrder: 0 SortOrder: 0
player3: player3:
Name: Player 3 Name: Player 3
SortOrder: 0 SortOrder: 0
GridFieldAction_SortOrder_VPlayer: UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_VPlayer:
player1: player1:
Name: Player 1 Name: Player 1
SortOrder: 0 SortOrder: 0
player2: player2:
Name: Player 2 Name: Player 2
SortOrder: 0 SortOrder: 0
player3: player3:
Name: Player 3 Name: Player 3
SortOrder: 0 SortOrder: 0
GridFieldAction_SortOrder_TestParent: UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_TestParent:
testparent: testparent:
Name: Test Name: Test
GridFieldAction_SortOrder_ChildObject: UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_ChildObject:
testitem1: testitem1:
Name: Test 1 Name: Test 1
SortOrder: 0 SortOrder: 0
Parent: =>GridFieldAction_SortOrder_TestParent.testparent Parent: =>UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_TestParent.testparent
testitem2: testitem2:
Name: Test 2 Name: Test 2
SortOrder: 0 SortOrder: 0
Parent: =>GridFieldAction_SortOrder_TestParent.testparent Parent: =>UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_TestParent.testparent
testitem3: testitem3:
Name: Test 3 Name: Test 3
SortOrder: 0 SortOrder: 0
Parent: =>GridFieldAction_SortOrder_TestParent.testparent Parent: =>UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_TestParent.testparent

View File

@ -1,171 +1,225 @@
<?php <?php
class GridFieldSortableRowsPageTest extends SapphireTest {
/** @var ArrayList */ namespace UndefinedOffset\SortableGridField\Tests;
protected $list;
/** @var GridField */ use SilverStripe\Control\Controller;
protected $gridField; use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\Session;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Dev\TestOnly;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig_Base;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject;
use SilverStripe\Versioned\Versioned;
use UndefinedOffset\SortableGridField\Forms\GridFieldSortableRows;
/** @var Form */ /**
protected $form; * Class GridFieldSortableRowsPageTest
*
* @package SortableGridField\Tests
*/
class GridFieldSortableRowsPageTest extends SapphireTest
{
/** @var ArrayList */
protected $list;
/** @var string */ /** @var GridField */
public static $fixture_file = 'GridFieldSortableRowsPageTest.yml'; protected $gridField;
/** @var array */ /** @var Form */
protected $extraDataObjects = array('GridFieldAction_PageSortOrder_Team', 'GridFieldAction_PageSortOrder_VTeam'); protected $form;
public function setUp() { /** @var string */
parent::setUp(); public static $fixture_file = 'sortablegridfield/tests/forms/GridFieldSortableRowsPageTest.yml';
$this->list = GridFieldAction_PageSortOrder_Team::get();
$config = GridFieldConfig_Base::create(5)->addComponent(new GridFieldSortableRows('SortOrder'));
$this->gridField = new GridField('testfield', 'testfield', $this->list, $config);
$this->form = new Form(new Controller(), 'mockform', new FieldList(array($this->gridField)), new FieldList());
}
public function testSortToNextPage() { /** @var array */
$this->gridField->State->GridFieldPaginator->currentPage=1; protected static $extra_dataobjects = array(
GridFieldAction_PageSortOrder_Team::class,
GridFieldAction_PageSortOrder_VTeam::class
);
public function setUp()
{
parent::setUp();
$this->list = GridFieldAction_PageSortOrder_Team::get();
$config = GridFieldConfig_Base::create(5)->addComponent(new GridFieldSortableRows('SortOrder'));
$this->gridField = new GridField('testfield', 'testfield', $this->list, $config);
$this->form = new Form(new SortableGridField_DummyController(), 'mockform', FieldList::create(array($this->gridField)), FieldList::create());
}
public function testSortToNextPage()
{
$this->gridField->State->GridFieldPaginator->currentPage = 1;
$team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team', 'team3');
$this->logInWithPermission('ADMIN');
$stateID = 'testGridStateActionField';
Session::set($stateID, array('grid' => '', 'actionName' => 'sortToPage', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true), 'GridFieldPaginator' => array('currentPage' => 1))));
$request = new HTTPRequest('POST', 'url', array('ItemID' => $team3->ID, 'Target' => 'nextpage'), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $this->form->getSecurityToken()->getName() => $this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID' => $stateID), $this->form, $request);
$team6 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team', 'team6');
$this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page');
$team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team', 'team3');
$this->assertEquals(6, $team3->SortOrder, 'Team 3 Should have moved to the top of the second page');
}
public function testSortToPrevPage()
{
$this->gridField->State->GridFieldPaginator->currentPage = 2;
$team7 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team', 'team7');
$this->logInWithPermission('ADMIN');
$stateID = 'testGridStateActionField';
Session::set($stateID, array('grid' => '', 'actionName' => 'sortToPage', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true), 'GridFieldPaginator' => array('currentPage' => 1))));
$request = new HTTPRequest('POST', 'url', array('ItemID' => $team7->ID, 'Target' => 'previouspage'), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $this->form->getSecurityToken()->getName() => $this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID' => $stateID), $this->form, $request);
$team3 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team3'); $team7 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team', 'team7');
$this->assertEquals(5, $team7->SortOrder, 'Team 7 Should have moved to the bottom of the first page');
$this->logInWithPermission('ADMIN'); $team5 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team', 'team5');
$stateID = 'testGridStateActionField'; $this->assertEquals(6, $team5->SortOrder, 'Team 5 Should have moved to the top of the second page');
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortToPage', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true), 'GridFieldPaginator'=>array('currentPage'=>1)))); }
$request = new SS_HTTPRequest('POST', 'url', array('ItemID'=>$team3->ID, 'Target'=>'nextpage'), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $this->form->getSecurityToken()->getName()=>$this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID'=>$stateID), $this->form, $request); public function testSortToNextPageVersioned()
{
//Force versioned to reset
Versioned::reset();
$list = GridFieldAction_PageSortOrder_VTeam::get();
$this->gridField->setList($list);
/** @var GridFieldSortableRows $sortableGrid */
$sortableGrid = $this->gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$sortableGrid->setUpdateVersionedStage('Live');
$this->gridField->State->GridFieldPaginator->currentPage = 1;
//Publish all records
foreach ($list as $item) {
$item->publish('Stage', 'Live');
}
$team6 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team6'); $team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam', 'team3');
$this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page');
$team3 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team3'); $this->logInWithPermission('ADMIN');
$this->assertEquals(6, $team3->SortOrder, 'Team 3 Should have moved to the top of the second page'); $stateID = 'testGridStateActionField';
} Session::set($stateID, array('grid' => '', 'actionName' => 'sortToPage', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true), 'GridFieldPaginator' => array('currentPage' => 1))));
$request = new HTTPRequest('POST', 'url', array('ItemID' => $team3->ID, 'Target' => 'nextpage'), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $this->form->getSecurityToken()->getName() => $this->form->getSecurityToken()->getValue()));
public function testSortToPrevPage() { $this->gridField->gridFieldAlterAction(array('StateID' => $stateID), $this->form, $request);
$this->gridField->State->GridFieldPaginator->currentPage=2;
$team7 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team7'); $team6 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam', 'team6');
$this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page on Versioned stage "Stage"');
$this->logInWithPermission('ADMIN'); $team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam', 'team3');
$stateID = 'testGridStateActionField'; $this->assertEquals(6, $team3->SortOrder, 'Team 3 Should have moved to the top of the second page on Versioned stage "Stage"');
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortToPage', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true), 'GridFieldPaginator'=>array('currentPage'=>1))));
$request = new SS_HTTPRequest('POST', 'url', array('ItemID'=>$team7->ID, 'Target'=>'previouspage'), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $this->form->getSecurityToken()->getName()=>$this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID'=>$stateID), $this->form, $request);
$team7 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team7'); $list = Versioned::get_by_stage(GridFieldAction_PageSortOrder_VTeam::class, 'Live');
$this->assertEquals(5, $team7->SortOrder, 'Team 7 Should have moved to the bottom of the first page');
$team5 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team5'); $team6 = $list->byID($team6->ID);
$this->assertEquals(6, $team5->SortOrder, 'Team 5 Should have moved to the top of the second page'); $this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page on Versioned stage "Live"');
}
public function testSortToNextPageVersioned() { $team3 = $list->byID($team3->ID);
//Force versioned to reset $this->assertEquals(6, $team3->SortOrder, 'Team 3 Should have moved to the top of the second page on Versioned stage "Live"');
Versioned::reset(); }
$list=GridFieldAction_PageSortOrder_VTeam::get(); public function testSortToPrevPageVersioned()
$this->gridField->setList($list); {
$this->gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setUpdateVersionedStage('Live'); //Force versioned to reset
$this->gridField->State->GridFieldPaginator->currentPage=1; Versioned::reset();
//Publish all records $list = GridFieldAction_PageSortOrder_VTeam::get();
foreach($list as $item) { $this->gridField->setList($list);
$item->publish('Stage', 'Live');
} /** @var GridFieldSortableRows $sortableGrid */
$sortableGrid = $this->gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$sortableGrid->setUpdateVersionedStage('Live');
$this->gridField->State->GridFieldPaginator->currentPage = 2;
//Publish all records
foreach ($list as $item) {
$item->publish('Stage', 'Live');
}
$team3 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team3'); $team7 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam', 'team7');
$this->logInWithPermission('ADMIN'); $this->logInWithPermission('ADMIN');
$stateID = 'testGridStateActionField'; $stateID = 'testGridStateActionField';
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortToPage', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true), 'GridFieldPaginator'=>array('currentPage'=>1)))); Session::set($stateID, array('grid' => '', 'actionName' => 'sortToPage', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true), 'GridFieldPaginator' => array('currentPage' => 1))));
$request = new SS_HTTPRequest('POST', 'url', array('ItemID'=>$team3->ID, 'Target'=>'nextpage'), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $this->form->getSecurityToken()->getName()=>$this->form->getSecurityToken()->getValue())); $request = new HTTPRequest('POST', 'url', array('ItemID' => $team7->ID, 'Target' => 'previouspage'), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $this->form->getSecurityToken()->getName() => $this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID'=>$stateID), $this->form, $request); $this->gridField->gridFieldAlterAction(array('StateID' => $stateID), $this->form, $request);
$team6 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team6'); $team7 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam', 'team7');
$this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page on Versioned stage "Stage"'); $this->assertEquals(5, $team7->SortOrder, 'Team 7 Should have moved to the bottom of the first page on Versioned stage "Stage"');
$team3 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team3'); $team5 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam', 'team5');
$this->assertEquals(6, $team3->SortOrder, 'Team 3 Should have moved to the top of the second page on Versioned stage "Stage"'); $this->assertEquals(6, $team5->SortOrder, 'Team 5 Should have moved to the top of the second page on Versioned stage "Stage"');
$list=Versioned::get_by_stage('GridFieldAction_PageSortOrder_VTeam', 'Live'); $list = Versioned::get_by_stage(GridFieldAction_PageSortOrder_VTeam::class, 'Live');
$team6 = $list->byID($team6->ID); $team7 = $list->byID($team7->ID);
$this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page on Versioned stage "Live"'); $this->assertEquals(5, $team7->SortOrder, 'Team 7 Should have moved to the bottom of the first page on Versioned stage "Live"');
$team3 = $list->byID($team3->ID); $team5 = $list->byID($team5->ID);
$this->assertEquals(6, $team3->SortOrder, 'Team 3 Should have moved to the top of the second page on Versioned stage "Live"'); $this->assertEquals(6, $team5->SortOrder, 'Team 5 Should have moved to the top of the second page on Versioned stage "Live"');
} }
public function testSortToPrevPageVersioned() {
//Force versioned to reset
Versioned::reset();
$list=GridFieldAction_PageSortOrder_VTeam::get();
$this->gridField->setList($list);
$this->gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setUpdateVersionedStage('Live');
$this->gridField->State->GridFieldPaginator->currentPage=2;
//Publish all records
foreach($list as $item) {
$item->publish('Stage', 'Live');
}
$team7 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team7');
$this->logInWithPermission('ADMIN');
$stateID = 'testGridStateActionField';
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortToPage', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true), 'GridFieldPaginator'=>array('currentPage'=>1))));
$request = new SS_HTTPRequest('POST', 'url', array('ItemID'=>$team7->ID, 'Target'=>'previouspage'), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $this->form->getSecurityToken()->getName()=>$this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID'=>$stateID), $this->form, $request);
$team7 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team7');
$this->assertEquals(5, $team7->SortOrder, 'Team 7 Should have moved to the bottom of the first page on Versioned stage "Stage"');
$team5 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team5');
$this->assertEquals(6, $team5->SortOrder, 'Team 5 Should have moved to the top of the second page on Versioned stage "Stage"');
$list=Versioned::get_by_stage('GridFieldAction_PageSortOrder_VTeam', 'Live');
$team7 = $list->byID($team7->ID);
$this->assertEquals(5, $team7->SortOrder, 'Team 7 Should have moved to the bottom of the first page on Versioned stage "Live"');
$team5 = $list->byID($team5->ID);
$this->assertEquals(6, $team5->SortOrder, 'Team 5 Should have moved to the top of the second page on Versioned stage "Live"');
}
} }
class GridFieldAction_PageSortOrder_Team extends DataObject implements TestOnly { /**
static $db = array( * Class GridFieldAction_PageSortOrder_Team
'Name' => 'Varchar', *
'City' => 'Varchar', * @package SortableGridField\Tests
'SortOrder' => 'Int' * @property string Name
); * @property string City
* @property int SortOrder
*/
class GridFieldAction_PageSortOrder_Team extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_PageSortOrder_Team';
static $default_sort='SortOrder'; private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar',
'SortOrder' => 'Int'
);
private static $default_sort = 'SortOrder';
} }
class GridFieldAction_PageSortOrder_VTeam extends DataObject implements TestOnly { /**
static $db = array( * Class GridFieldAction_PageSortOrder_VTeam
'Name' => 'Varchar', *
'City' => 'Varchar', * @package SortableGridField\Tests
'SortOrder' => 'Int' * @property string Name
); * @property string City
* @property int SortOrder
*/
class GridFieldAction_PageSortOrder_VTeam extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_PageSortOrder_VTeam';
static $default_sort='SortOrder'; private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar',
'SortOrder' => 'Int'
);
static $extensions=array( private static $default_sort = 'SortOrder';
"Versioned('Stage', 'Live')"
); private static $extensions = array(
"SilverStripe\\Versioned\\Versioned('Stage', 'Live')"
);
} }
?>

View File

@ -1,75 +1,75 @@
GridFieldAction_PageSortOrder_Team: UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team:
team1: team1:
Name: Team 1 Name: Team 1
City: Cologne City: Cologne
SortOrder: 1 SortOrder: 1
team2: team2:
Name: Team 2 Name: Team 2
City: Wellington City: Wellington
SortOrder: 2 SortOrder: 2
team3: team3:
Name: Team 3 Name: Team 3
City: Auckland City: Auckland
SortOrder: 3 SortOrder: 3
team4: team4:
Name: Team 4 Name: Team 4
City: Cologne City: Cologne
SortOrder: 4 SortOrder: 4
team5: team5:
Name: Team 5 Name: Team 5
City: Wellington City: Wellington
SortOrder: 5 SortOrder: 5
team6: team6:
Name: Team 6 Name: Team 6
City: Auckland City: Auckland
SortOrder: 6 SortOrder: 6
team7: team7:
Name: Team 7 Name: Team 7
City: Cologne City: Cologne
SortOrder: 7 SortOrder: 7
team8: team8:
Name: Team 8 Name: Team 8
City: Wellington City: Wellington
SortOrder: 8 SortOrder: 8
team9: team9:
Name: Team 9 Name: Team 9
City: Auckland City: Auckland
SortOrder: 9 SortOrder: 9
GridFieldAction_PageSortOrder_VTeam: UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam:
team1: team1:
Name: Team 1 Name: Team 1
City: Cologne City: Cologne
SortOrder: 1 SortOrder: 1
team2: team2:
Name: Team 2 Name: Team 2
City: Wellington City: Wellington
SortOrder: 2 SortOrder: 2
team3: team3:
Name: Team 3 Name: Team 3
City: Auckland City: Auckland
SortOrder: 3 SortOrder: 3
team4: team4:
Name: Team 4 Name: Team 4
City: Cologne City: Cologne
SortOrder: 4 SortOrder: 4
team5: team5:
Name: Team 5 Name: Team 5
City: Wellington City: Wellington
SortOrder: 5 SortOrder: 5
team6: team6:
Name: Team 6 Name: Team 6
City: Auckland City: Auckland
SortOrder: 6 SortOrder: 6
team7: team7:
Name: Team 7 Name: Team 7
City: Cologne City: Cologne
SortOrder: 7 SortOrder: 7
team8: team8:
Name: Team 8 Name: Team 8
City: Wellington City: Wellington
SortOrder: 8 SortOrder: 8
team9: team9:
Name: Team 9 Name: Team 9
City: Auckland City: Auckland
SortOrder: 9 SortOrder: 9

View File

@ -1,106 +1,156 @@
<?php <?php
class GridFieldSortableRowsTest extends SapphireTest {
/** @var ArrayList */ namespace UndefinedOffset\SortableGridField\Tests;
protected $list;
/** @var GridField */ use SilverStripe\Control\HTTPRequest;
protected $gridField; use SilverStripe\Control\Session;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Dev\TestOnly;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\ValidationException;
use SilverStripe\Security\Member;
use SilverStripe\Versioned\Versioned;
use UndefinedOffset\SortableGridField\Forms\GridFieldSortableRows;
/** @var Form */ class GridFieldSortableRowsTest extends SapphireTest
protected $form; {
/** @var ArrayList */
protected $list;
/** @var string */ /** @var GridField */
public static $fixture_file = 'GridFieldSortableRowsTest.yml'; protected $gridField;
/** @var array */ /** @var Form */
protected $extraDataObjects = array('GridFieldAction_SortOrder_Team', 'GridFieldAction_SortOrder_VTeam'); protected $form;
public function setUp() { /** @var string */
parent::setUp(); public static $fixture_file = 'sortablegridfield/tests/forms/GridFieldSortableRowsTest.yml';
$this->list = GridFieldAction_SortOrder_Team::get();
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
$this->gridField = new GridField('testfield', 'testfield', $this->list, $config);
$this->form = new Form(new Controller(), 'mockform', new FieldList(array($this->gridField)), new FieldList());
}
public function testSortActionWithoutCorrectPermission() { /** @var array */
if(Member::currentUser()) { Member::currentUser()->logOut(); } protected static $extra_dataobjects = array(
$this->setExpectedException('ValidationException'); GridFieldAction_SortOrder_Team::class,
$team1 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team1'); GridFieldAction_SortOrder_VTeam::class
$team2 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team2'); );
$team3 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team3');
$stateID = 'testGridStateActionField'; public function setUp()
Session::set($stateID, array('grid'=>'', 'actionName'=>'saveGridRowSort', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); {
$request = new SS_HTTPRequest('POST', 'url', array('ItemIDs'=>"$team1->ID, $team3->ID, $team2->ID"), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $this->form->getSecurityToken()->getName()=>$this->form->getSecurityToken()->getValue())); parent::setUp();
$this->gridField->gridFieldAlterAction(array('StateID'=>$stateID), $this->form, $request); $this->list = GridFieldAction_SortOrder_Team::get();
$this->assertEquals($team3->ID, $this->list->last()->ID, 'User should\'t be able to sort records without correct permissions.'); $config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
} $this->gridField = new GridField('testfield', 'testfield', $this->list, $config);
$this->form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($this->gridField)), new FieldList());
}
public function testSortActionWithAdminPermission() { public function testSortActionWithoutCorrectPermission()
$team1 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team1'); {
$team2 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team2'); if (Member::currentUser()) {
$team3 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team3'); Member::currentUser()->logOut();
$this->logInWithPermission('ADMIN'); }
$stateID = 'testGridStateActionField'; $this->setExpectedException(ValidationException::class);
Session::set($stateID, array('grid'=>'', 'actionName'=>'saveGridRowSort', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); $team1 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team', 'team1');
$request = new SS_HTTPRequest('POST', 'url', array('ItemIDs'=>"$team1->ID, $team3->ID, $team2->ID"), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $this->form->getSecurityToken()->getName()=>$this->form->getSecurityToken()->getValue())); $team2 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team', 'team2');
$this->gridField->gridFieldAlterAction(array('StateID'=>$stateID), $this->form, $request); $team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team', 'team3');
$this->assertEquals($team2->ID, $this->list->last()->ID, 'User should be able to sort records with ADMIN permission.');
}
public function testSortActionVersioned() { $stateID = 'testGridStateActionField';
//Force versioned to reset Session::set($stateID, array('grid' => '', 'actionName' => 'saveGridRowSort', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
Versioned::reset(); $request = new HTTPRequest('POST', 'url', array('ItemIDs' => "$team1->ID, $team3->ID, $team2->ID"), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $this->form->getSecurityToken()->getName() => $this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID' => $stateID), $this->form, $request);
$this->assertEquals($team3->ID, $this->list->last()->ID, 'User should\'t be able to sort records without correct permissions.');
}
$list = GridFieldAction_SortOrder_VTeam::get(); public function testSortActionWithAdminPermission()
$this->gridField->setList($list); {
$this->gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setUpdateVersionedStage('Live'); $team1 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team', 'team1');
$team2 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team', 'team2');
$team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team', 'team3');
$this->logInWithPermission('ADMIN');
$stateID = 'testGridStateActionField';
Session::set($stateID, array('grid' => '', 'actionName' => 'saveGridRowSort', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
$request = new HTTPRequest('POST', 'url', array('ItemIDs' => "$team1->ID, $team3->ID, $team2->ID"), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $this->form->getSecurityToken()->getName() => $this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID' => $stateID), $this->form, $request);
$this->assertEquals($team2->ID, $this->list->last()->ID, 'User should be able to sort records with ADMIN permission.');
}
//Publish all records public function testSortActionVersioned()
foreach($list as $item) { {
$item->publish('Stage', 'Live'); //Force versioned to reset
} Versioned::reset();
$team1 = $this->objFromFixture('GridFieldAction_SortOrder_VTeam', 'team1'); $list = GridFieldAction_SortOrder_VTeam::get();
$team2 = $this->objFromFixture('GridFieldAction_SortOrder_VTeam', 'team2'); $this->gridField->setList($list);
$team3 = $this->objFromFixture('GridFieldAction_SortOrder_VTeam', 'team3');
$this->logInWithPermission('ADMIN'); /** @var GridFieldSortableRows $sortableGrid */
$stateID = 'testGridStateActionField'; $sortableGrid = $this->gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
Session::set($stateID, array('grid'=>'', 'actionName'=>'saveGridRowSort', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); $sortableGrid->setUpdateVersionedStage('Live');
$request = new SS_HTTPRequest('POST', 'url', array('ItemIDs'=>"$team1->ID, $team3->ID, $team2->ID"), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $this->form->getSecurityToken()->getName()=>$this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID'=>$stateID), $this->form, $request);
$this->assertEquals($team2->ID, $list->last()->ID, 'Sort should have happened on Versioned stage "Stage"'); //Publish all records
foreach ($list as $item) {
$item->publish('Stage', 'Live');
}
$list=Versioned::get_by_stage('GridFieldAction_SortOrder_VTeam', 'Live'); $team1 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_VTeam', 'team1');
$this->assertEquals($team2->ID, $list->last()->ID, 'Sort should have happened on Versioned stage "Live"'); $team2 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_VTeam', 'team2');
} $team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_VTeam', 'team3');
$this->logInWithPermission('ADMIN');
$stateID = 'testGridStateActionField';
Session::set($stateID, array('grid' => '', 'actionName' => 'saveGridRowSort', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
$request = new HTTPRequest('POST', 'url', array('ItemIDs' => "$team1->ID, $team3->ID, $team2->ID"), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $this->form->getSecurityToken()->getName() => $this->form->getSecurityToken()->getValue()));
$this->gridField->gridFieldAlterAction(array('StateID' => $stateID), $this->form, $request);
$this->assertEquals($team2->ID, $list->last()->ID, 'Sort should have happened on Versioned stage "Stage"');
$list = Versioned::get_by_stage(GridFieldAction_SortOrder_VTeam::class, 'Live');
$this->assertEquals($team2->ID, $list->last()->ID, 'Sort should have happened on Versioned stage "Live"');
}
} }
class GridFieldAction_SortOrder_Team extends DataObject implements TestOnly { /**
static $db = array( * Class GridFieldAction_SortOrder_Team
'Name' => 'Varchar', *
'City' => 'Varchar', * @package SortableGridField\Tests
'SortOrder' => 'Int' * @property string Name
); * @property string City
* @property int SortOrder
*/
class GridFieldAction_SortOrder_Team extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_Team';
static $default_sort='SortOrder'; private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar',
'SortOrder' => 'Int'
);
private static $default_sort = 'SortOrder';
} }
class GridFieldAction_SortOrder_VTeam extends DataObject implements TestOnly { /**
static $db = array( * Class GridFieldAction_SortOrder_VTeam
'Name' => 'Varchar', *
'City' => 'Varchar', * @package SortableGridField\Tests
'SortOrder' => 'Int' * @property string Name
); * @property string City
* @property int SortOrder
*/
class GridFieldAction_SortOrder_VTeam extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_VTeam';
static $default_sort='SortOrder'; private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar',
'SortOrder' => 'Int'
);
private static $default_sort = 'SortOrder';
static $extensions=array( private static $extensions = array(
"Versioned('Stage', 'Live')" "SilverStripe\\Versioned\\Versioned('Stage', 'Live')"
); );
} }
?>

View File

@ -1,27 +1,27 @@
GridFieldAction_SortOrder_Team: UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team:
team1: team1:
Name: Team 1 Name: Team 1
City: Cologne City: Cologne
SortOrder: 1 SortOrder: 1
team2: team2:
Name: Team 2 Name: Team 2
City: Wellington City: Wellington
SortOrder: 2 SortOrder: 2
team3: team3:
Name: Team 3 Name: Team 3
City: Auckland City: Auckland
SortOrder: 3 SortOrder: 3
GridFieldAction_SortOrder_VTeam: UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_VTeam:
team1: team1:
Name: Team 1 Name: Team 1
City: Cologne City: Cologne
SortOrder: 1 SortOrder: 1
team2: team2:
Name: Team 2 Name: Team 2
City: Wellington City: Wellington
SortOrder: 2 SortOrder: 2
team3: team3:
Name: Team 3 Name: Team 3
City: Auckland City: Auckland
SortOrder: 3 SortOrder: 3