Fixes bug

JS formatting

Updated README.md

SS4 Compliance & Updated Tests

Namespaced templates

Update .travis.yml, .scrutinizer.yml

Update composer.json
This commit is contained in:
Reece 2017-05-27 14:45:28 +10:00 committed by UndefinedOffset
parent 1862700761
commit 23da810b19
15 changed files with 1847 additions and 1549 deletions

View File

@ -66,4 +66,4 @@ checks:
argument_type_checks: true argument_type_checks: true
filter: filter:
paths: [code/*, tests/*] paths: [src/*, tests/*]

View File

@ -1,23 +1,22 @@
language: php language: php
sudo: false php:
- 5.6
- 7.0
- 7.1
env:
- DB=MYSQL CORE_RELEASE=4
matrix: matrix:
include: include:
- php: 5.6 - php: 7.1
env: DB=PGSQL CORE_RELEASE=3.5 env: DB=PGSQL CORE_RELEASE=4
- php: 5.6
env: DB=SQLITE3 CORE_RELEASE=3.5
- php: 5.6
env: DB=MYSQL CORE_RELEASE=3.5
- php: 5.3
env: DB=MYSQL CORE_RELEASE=3.1
before_script: before_script:
- phpenv rehash - git clone git://github.com/silverstripe/silverstripe-travis-support.git ~/travis-support
- git clone git://github.com/silverstripe-labs/silverstripe-travis-support.git ~/travis-support - php ~/travis-support/travis_setup.php --source `pwd` --target ~/builds/ss
- php ~/travis-support/travis_setup.php --source `pwd` --target ~/builds/ss - cd ~/builds/ss
- cd ~/builds/ss
script: script:
- phpunit sortablegridfield/tests/ - vendor/bin/phpunit sortablegridfield/tests

View File

@ -2,20 +2,19 @@ SortableGridField
================= =================
[![Build Status](https://travis-ci.org/UndefinedOffset/SortableGridField.png)](https://travis-ci.org/UndefinedOffset/SortableGridField) ![helpfulrobot](https://helpfulrobot.io/undefinedoffset/sortablegridfield/badge) [![Build Status](https://travis-ci.org/UndefinedOffset/SortableGridField.png)](https://travis-ci.org/UndefinedOffset/SortableGridField) ![helpfulrobot](https://helpfulrobot.io/undefinedoffset/sortablegridfield/badge)
Adds drag and drop functionality to SilverStripe 3's GridField Adds drag and drop functionality to SilverStripe 4's GridField
## Requirements ## Requirements
* SilverStripe 3.x * SilverStripe 4.x
## Installation ## Installation
__Composer (recommended):__
``` Installation is supported via composer only
```sh
composer require undefinedoffset/sortablegridfield composer require undefinedoffset/sortablegridfield
``` ```
If you prefer you may also install manually:
* Download the module from here https://github.com/UndefinedOffset/SortableGridField/archive/master.zip
* Extract the downloaded archive into your site root so that the destination folder is called SortableGridField, opening the extracted folder should contain _config.php in the root along with other files/folders
* Run dev/build?flush=all to regenerate the manifest * Run dev/build?flush=all to regenerate the manifest
* Upon entering the cms and using GridFieldSortableRows component for the first time you make need to add ?flush=all to the end of the address to force the templates to regenerate * Upon entering the cms and using GridFieldSortableRows component for the first time you make need to add ?flush=all to the end of the address to force the templates to regenerate
@ -69,23 +68,14 @@ $sortable->setCustomRelationName('MyRelationship');
``` ```
## Migrating from SilverStripe 2.4 and Data Object Manager's SortableDataObject
SortableGridField is not the same as SortableDataObject, since it is only a component of GridField it does not have the ability to catch the object when it is saved for the first time. So SortableGridField uses 1 as the first sort index because 0 is the default for an integer field/column in the database. For migrations from 2.4 with SortableDataObject you need to setup your DataObject based on the instructions above however you must name your sort column "SortOrder" to maintain your sort indexes defined by SortableDataObject. Then you need to run the following query on the table containing your sort field, for many_many relationships this will be something like {RelationshipClass}_{RelationshipName}. This query will maintain your sort order from SortableDataObject but increment the index by 1 giving it a starting number of 1.
```sql
UPDATE YourTable SET SortOrder=SortOrder+1;
```
## Reporting an issue ## Reporting an issue
When you're reporting an issue please ensure you specify what version of SilverStripe you are using i.e. 3.0.5, 3.1beta3, 3.0-master etc. Also be sure to include any JavaScript or PHP errors you receive, for PHP errors please ensure you include the full stack trace. Also please include your implementation code (where your setting up your grid field) as well as how you produced the issue. You may also be asked to provide some of the classes to aid in re-producing the issue. Stick with the issue, remember that you seen the issue not the maintainer of the module so it may take allot of questions to arrive at a fix or answer. When you're reporting an issue please ensure you specify what version of SilverStripe you are using i.e. 3.0.5, 3.1beta3, 3.0-master etc. Also be sure to include any JavaScript or PHP errors you receive, for PHP errors please ensure you include the full stack trace. Also please include your implementation code (where your setting up your grid field) as well as how you produced the issue. You may also be asked to provide some of the classes to aid in re-producing the issue. Stick with the issue, remember that you seen the issue not the maintainer of the module so it may take allot of questions to arrive at a fix or answer.
### Notes ### Notes
* When using with GridFieldManyRelationHandler make sure that you add GridFieldSortableRows to your config before for example GridFieldManyRelationHandler: * When using with GridFieldManyRelationHandler make sure that you add GridFieldSortableRows to your config before for example GridFieldManyRelationHandler:
```php
```php $config->addComponent(new GridFieldSortableRows('SortOrder'), 'GridFieldManyRelationHandler');
$config->addComponent(new GridFieldSortableRows('SortOrder'), 'GridFieldManyRelationHandler'); ```
```
## Contributing ## Contributing

View File

@ -1,3 +1,2 @@
<?php <?php
define('SORTABLE_GRIDFIELD_BASE', basename(dirname(__FILE__))); define('SORTABLE_GRIDFIELD_BASE', basename(dirname(__FILE__)));
?>

View File

@ -1,6 +1,6 @@
{ {
"name": "undefinedoffset/sortablegridfield", "name": "undefinedoffset/sortablegridfield",
"description": "Adds drag and drop functionality to SilverStripe 3.0's GridField", "description": "Adds drag and drop functionality to SilverStripe 4.x's GridField",
"type": "silverstripe-module", "type": "silverstripe-module",
"keywords": ["silverstripe", "gridfield"], "keywords": ["silverstripe", "gridfield"],
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
@ -11,15 +11,24 @@
"role": "Developer" "role": "Developer"
} }
], ],
"require": "require": {
{ "silverstripe/admin": "^1.0@dev",
"silverstripe/framework": ">=3.0.1", "silverstripe/framework": "^4.0@dev",
"composer/installers": "*" "silverstripe/versioned": "^1.0"
},
"autoload": {
"psr-4": {
"UndefinedOffset\\SortableGridField\\": "src/",
"UndefinedOffset\\SortableGridField\\Tests\\": "tests/"
}
}, },
"support": { "support": {
"issues": "https://github.com/undefinedoffset/SortableGridField/issues" "issues": "https://github.com/undefinedoffset/SortableGridField/issues"
}, },
"extra": { "extra": {
"installer-name": "sortablegridfield" "installer-name": "sortablegridfield",
"branch-alias": {
"dev-master": "1.0.x-dev"
}
} }
} }

View File

@ -1,202 +1,206 @@
(function($) { (function ($) {
$.entwine('ss', function($) { $.entwine('ss', function ($) {
$('.ss-gridfield .gridfield-sortablerows input').entwine({ $('.ss-gridfield .gridfield-sortablerows input').entwine({
PageSort: false, PageSort: false,
onmatch: function() { onmatch: function () {
var self=this; var self = this;
var refCheckbox=$(this); var refCheckbox = $(this);
var gridField=this.getGridField(); var gridField = this.getGridField();
var form=gridField.closest('form'); var form = gridField.closest('form');
var pageArrows=gridField.find('.gridfield-sortablerows-movepage .sortablerows-psort-arrow'); var pageArrows = gridField.find('.gridfield-sortablerows-movepage .sortablerows-psort-arrow');
if($(this).is(':checked')) { if ($(this).is(':checked')) {
gridField.find('table').addClass('dragSorting'); gridField.find('table').addClass('dragSorting');
}else { } else {
gridField.find('table').removeClass('dragSorting'); gridField.find('table').removeClass('dragSorting');
} }
gridField.find('tbody').sortable({ gridField.find('tbody').sortable({
opacity: 0.6, opacity: 0.6,
disabled: ($(this).is(':checked')==false), disabled: ($(this).is(':checked') == false),
start: function(event, ui) { start: function (event, ui) {
pageArrows.show(); pageArrows.show();
pageArrows.redraw(); pageArrows.redraw();
pageArrows.startMoveTracking(); pageArrows.startMoveTracking();
}, },
stop: function(event, ui) { stop: function (event, ui) {
pageArrows.stopMoveTracking(); pageArrows.stopMoveTracking();
pageArrows.hide(); pageArrows.hide();
}, },
sort: function(event, ui) { sort: function (event, ui) {
pageArrows.moveTracking(event, ui); pageArrows.moveTracking(event, ui);
}, },
update: function(event, ui) { update: function (event, ui) {
if(self.getPageSort()) { if (self.getPageSort()) {
self.setPageSort(false); self.setPageSort(false);
return; return;
} }
var gridItems=gridField.getItems(); var gridItems = gridField.getItems();
gridItems.removeClass('first last odd even'); gridItems.removeClass('first last odd even');
gridItems.first().addClass('first'); gridItems.first().addClass('first');
gridItems.last().addClass('last'); gridItems.last().addClass('last');
gridItems.filter(':even').addClass('odd'); gridItems.filter(':even').addClass('odd');
gridItems.filter(':odd').addClass('even'); gridItems.filter(':odd').addClass('even');
var dataRows=[]; var dataRows = [];
var button=refCheckbox.parent().find('.sortablerows-savesort'); var button = refCheckbox.parent().find('.sortablerows-savesort');
for(var i=0;i<gridItems.length;i++) { for (var i = 0; i < gridItems.length; i++) {
dataRows[i]=$(gridItems[i]).data('id'); dataRows[i] = $(gridItems[i]).data('id');
} }
self._makeRequest({data: [ self._makeRequest({
{ data: [
name: button.attr('name'), {
value: button.val() name: button.attr('name'),
}, value: button.val()
{ },
name: 'ItemIDs', {
value: dataRows name: 'ItemIDs',
} value: dataRows
]},function() { }
form.removeClass('loading'); ]
}); }, function () {
} form.removeClass('loading');
}); });
}
if(refCheckbox.hasClass('gridfield-sortablerows-noselection') || $(this).is(':checked')) { });
gridField.find('tbody').disableSelection();
} if (refCheckbox.hasClass('gridfield-sortablerows-noselection') || $(this).is(':checked')) {
}, gridField.find('tbody').disableSelection();
}
onchange: function(e) { },
var gridField=this.getGridField();
gridField.find('tbody').sortable('option', 'disabled', ($(this).is(':checked')==false)); onchange: function (e) {
gridField.setState('GridFieldSortableRows', {sortableToggle: $(this).is(':checked')}); var gridField = this.getGridField();
gridField.find('tbody').sortable('option', 'disabled', ($(this).is(':checked') == false));
gridField.setState('GridFieldSortableRows', {sortableToggle: $(this).is(':checked')});
var button=$(this).parent().find('.sortablerows-toggle');
gridField.reload({data: [{name: button.attr('name'), value: button.val()}]});
}, var button = $(this).parent().find('.sortablerows-toggle');
gridField.reload({data: [{name: button.attr('name'), value: button.val()}]});
_makeRequest: function(ajaxOpts, callback) { },
var gridField=this.getGridField();
var form = gridField.closest('form'); _makeRequest: function (ajaxOpts, callback) {
var gridField = this.getGridField();
form.addClass('loading'); var form = gridField.closest('form');
ajaxOpts.data = ajaxOpts.data.concat(form.find(':input').serializeArray()); form.addClass('loading');
// Include any GET parameters from the current URL, as the view state might depend on it. ajaxOpts.data = ajaxOpts.data.concat(form.find(':input').serializeArray());
// For example, a list prefiltered through external search criteria might be passed to GridField.
if(window.location.search) { // Include any GET parameters from the current URL, as the view state might depend on it.
ajaxOpts.data = window.location.search.replace(/^\?/, '') + '&' + $.param(ajaxOpts.data); // For example, a list prefiltered through external search criteria might be passed to GridField.
} if (window.location.search) {
ajaxOpts.data = window.location.search.replace(/^\?/, '') + '&' + $.param(ajaxOpts.data);
$.ajax($.extend({}, { }
headers: {"X-Pjax" : 'CurrentField'},
type: "POST", $.ajax($.extend({}, {
url: gridField.data('url'), headers: {"X-Pjax": 'CurrentField'},
dataType: 'html', type: "POST",
success: callback, url: gridField.data('url'),
error: function(e) { dataType: 'html',
alert(ss.i18n._t('GRIDFIELD.ERRORINTRANSACTION')); success: callback,
} error: function (e) {
}, ajaxOpts)); alert(ss.i18n._t('GRIDFIELD.ERRORINTRANSACTION'));
} }
}); }, ajaxOpts));
}
$('.ss-gridfield .gridfield-sortablerows-movepage .sortablerows-psort-arrow').entwine({ });
ArrowIcon: null,
$('.ss-gridfield .gridfield-sortablerows-movepage .sortablerows-psort-arrow').entwine({
onmatch: function() { ArrowIcon: null,
var gridField=this.getGridField();
var sortableCheckbox=gridField.find('.gridfield-sortablerows input'); onmatch: function () {
var self=$(this); var gridField = this.getGridField();
var sortableCheckbox = gridField.find('.gridfield-sortablerows input');
if($(this).hasClass('sortablerows-prev-page') && (gridField.find('.ss-gridfield-previouspage').length==0 || gridField.find('.ss-gridfield-previouspage').is(':disabled'))) { var self = $(this);
$(this).remove();
return; if ($(this).hasClass('sortablerows-prev-page') && (gridField.find('.ss-gridfield-previouspage').length == 0 || gridField.find('.ss-gridfield-previouspage').is(':disabled'))) {
}else if($(this).hasClass('sortablerows-next-page') && (gridField.find('.ss-gridfield-nextpage').length==0 || gridField.find('.ss-gridfield-nextpage').is(':disabled'))) { $(this).remove();
$(this).remove(); return;
return; } else if ($(this).hasClass('sortablerows-next-page') && (gridField.find('.ss-gridfield-nextpage').length == 0 || gridField.find('.ss-gridfield-nextpage').is(':disabled'))) {
} $(this).remove();
return;
$(this).droppable({ }
disabled: $(this).is(':disabled'),
accept: 'tr.ss-gridfield-item', $(this).droppable({
activeClass: 'sortablerows-droptarget', disabled: $(this).is(':disabled'),
tolerance: 'pointer', accept: 'tr.ss-gridfield-item',
drop: function(event, ui) { activeClass: 'sortablerows-droptarget',
self.stopMoveTracking(); tolerance: 'pointer',
drop: function (event, ui) {
sortableCheckbox.setPageSort(true); self.stopMoveTracking();
var button=gridField.find('.gridfield-sortablerows .sortablerows-sorttopage'); sortableCheckbox.setPageSort(true);
var itemID=$(ui.draggable).data('id');
var target=''; var button = gridField.find('.gridfield-sortablerows .sortablerows-sorttopage');
var itemID = $(ui.draggable).data('id');
if($(this).hasClass('sortablerows-prev-page')) { var target = '';
target='previouspage';
}else if($(this).hasClass('sortablerows-next-page')) { if ($(this).hasClass('sortablerows-prev-page')) {
target='nextpage'; target = 'previouspage';
} } else if ($(this).hasClass('sortablerows-next-page')) {
target = 'nextpage';
}
//Move and Reload the grid
gridField.reload({data: [
{ //Move and Reload the grid
name: button.attr('name'), gridField.reload({
value: button.val() data: [
}, {
{ name: button.attr('name'),
name: 'ItemID', value: button.val()
value: itemID },
}, {
{ name: 'ItemID',
name: 'Target', value: itemID
value: target },
} {
]}); name: 'Target',
} value: target
}); }
]
this.redraw(); });
}, }
redraw: function() { });
var gridField=this.getGridField();
var tbody=gridField.find('tbody'); this.redraw();
var tbodyPos=tbody.position(); },
redraw: function () {
$(this).css('top', tbodyPos.top+'px').height(tbody.height()); var gridField = this.getGridField();
}, var tbody = gridField.find('tbody');
startMoveTracking: function() { var tbodyPos = tbody.position();
var self=$(this);
self.setArrowIcon(self.find('i')); $(this).css('top', tbodyPos.top + 'px').height(tbody.height());
}, },
stopMoveTracking: function() { startMoveTracking: function () {
$(this).setArrowIcon(null); var self = $(this);
}, self.setArrowIcon(self.find('i'));
moveTracking: function(e, ui) { },
var self=$(this); stopMoveTracking: function () {
var arrowIcon=self.getArrowIcon(); $(this).setArrowIcon(null);
if(arrowIcon) { },
var selfOffset=self.offset().top; moveTracking: function (e, ui) {
var arrowIconHeight=arrowIcon.width()+10; var self = $(this);
var railHeight=self.height()-arrowIconHeight; var arrowIcon = self.getArrowIcon();
var helperPos=ui.helper.offset().top; if (arrowIcon) {
var selfOffset = self.offset().top;
if(helperPos>selfOffset+10 && helperPos<selfOffset+railHeight) { var arrowIconHeight = arrowIcon.width() + 10;
arrowIcon.css('top', ((helperPos-selfOffset)+arrowIconHeight/2)+'px'); var railHeight = self.height() - arrowIconHeight;
} var helperPos = ui.helper.offset().top;
}
} if (helperPos > selfOffset + 10 && helperPos < selfOffset + railHeight) {
}); arrowIcon.css('top', ((helperPos - selfOffset) + arrowIconHeight / 2) + 'px');
}); }
}
}
});
});
})(jQuery); })(jQuery);

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 */
* @param string $sortColumn Column that should be used to update the sort information protected $disable_selection = true;
* @param bool $disableSelection Disable selection on the GridField when dragging
* @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 __construct($sortColumn, $disableSelection = true, $updateVersionStage = null, $customRelationName = null) {
$this->sortColumn = $sortColumn;
$this->disable_selection = $disableSelection;
$this->update_versioned_stage = $updateVersionStage;
$this->custom_relation_name = $customRelationName;
}
/**
* 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
* @return Array Map where the keys are fragment names and the values are pieces of HTML to add to these fragments.
*/
public function getHTMLFragments($gridField) {
$dataList = $gridField->getList();
if(class_exists('UnsavedRelationList') && $dataList instanceof UnsavedRelationList) { /** @var bool */
return array(); protected $append_to_top = false;
}
$state = $gridField->State->GridFieldSortableRows;
if(!is_bool($state->sortableToggle)) {
$state->sortableToggle = false;
}
//Ensure user can edit
if(!singleton($gridField->getModelClass())->canEdit()){
return array();
}
//Sort order toggle
$sortOrderToggle = GridField_FormAction::create(
$gridField,
'sortablerows-toggle',
'sorttoggle',
'sortableRowsToggle',
null
)->addExtraClass('sortablerows-toggle');
$sortOrderSave = GridField_FormAction::create(
$gridField,
'sortablerows-savesort',
'savesort',
'saveGridRowSort',
null
)->addExtraClass('sortablerows-savesort');
//Sort to Page Action
$sortToPage = GridField_FormAction::create(
$gridField,
'sortablerows-sorttopage',
'sorttopage',
'sortToPage',
null
)->addExtraClass('sortablerows-sorttopage');
$data = array('SortableToggle' => $sortOrderToggle,
'SortOrderSave' => $sortOrderSave,
'SortToPage' => $sortToPage,
'Checked' => ($state->sortableToggle == true ? ' checked = "checked"':''),
'List' => $dataList);
$forTemplate = new ArrayData($data);
//Inject Requirements
$custom = Config::inst()->get('GridFieldSortableRows', 'Base');
$base = $custom ?: SORTABLE_GRIDFIELD_BASE;
Requirements::css($base . '/css/GridFieldSortableRows.css'); /** @var null|string */
Requirements::javascript($base . '/javascript/GridFieldSortableRows.js'); protected $update_versioned_stage = null;
$args = array('Colspan' => count($gridField->getColumns()), 'ID' => $gridField->ID(), 'DisableSelection' => $this->disable_selection);
$fragments=array('header' => $forTemplate->renderWith('GridFieldSortableRows', $args));
if($gridField->getConfig()->getComponentByType('GridFieldPaginator')) {
$fragments['after']=$forTemplate->renderWith('GridFieldSortableRows_paginator');
}
return $fragments;
}
/**
* Manipulate the datalist as needed by this grid modifier.
* @param GridField $gridField Grid Field Reference
* @param SS_List $dataList Data List to adjust
* @return DataList Modified Data List
*/
public function getManipulatedData(GridField $gridField, SS_List $dataList) {
//Detect and correct items with a sort column value of 0 (push to bottom)
$this->fixSortColumn($gridField, $dataList);
$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)) {
return $dataList->sort($headerState->SortColumn, $headerState->SortDirection);
}
if ($state->sortableToggle === true) {
$gridField->getConfig()->removeComponentsByType('GridFieldFilterHeader');
$gridField->getConfig()->removeComponentsByType('GridFieldSortableHeader');
}
return $dataList->sort($this->sortColumn);
}
/**
* Sets if new records should be appended to the top or the bottom of the list
* @param bool $value Boolean true to append to the top false to append to the bottom
* @return GridFieldSortableRows Returns the current instance
*/
public function setAppendToTop($value) {
$this->append_to_top=$value;
return $this;
}
/**
* @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){
$this->disable_selection = $value;
return $this;
}
/**
* Sets the suffix of the versioned stage that should be updated along side the default stage
* @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) {
$this->update_versioned_stage=$value;
return $this;
}
/**
* 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
*/
public function setCustomRelationName($value) {
$this->custom_relation_name=$value;
return $this;
}
/**
* 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
* @param SS_List $dataList Data List of items to be checked
*/
protected function fixSortColumn($gridField, SS_List $dataList) {
if(class_exists('UnsavedRelationList') && $dataList instanceof UnsavedRelationList) {
return;
}
$list=clone $dataList;
$list=$list->alterDataQuery(function($query, SS_List $tmplist) {
$query->limit(array());
return $query;
});
$many_many = ($list instanceof ManyManyList);
if (!$many_many) {
$sng=singleton($gridField->getModelClass());
$fieldType=$sng->db($this->sortColumn);
if(!$fieldType || !(strtolower($fieldType) == 'int' || is_subclass_of($fieldType, 'Int'))) {
if(is_array($fieldType)) {
user_error('Sort column '.$this->sortColumn.' could not be found in '.$gridField->getModelClass().'\'s ancestry', E_USER_ERROR);
}else {
user_error('Sort column '.$this->sortColumn.' must be an Int, column is of type '.$fieldType, E_USER_ERROR);
}
exit;
}
}
$max = $list->Max($this->sortColumn);
$list=$list->filter($this->sortColumn, 0)->sort("Created,ID");
if($list->Count()>0) {
$owner = $gridField->Form->getRecord();
$sortColumn = $this->sortColumn;
$i = 1;
if ($many_many) {
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(!$extraFields || !array_key_exists($this->sortColumn, $extraFields) || !($extraFields[$this->sortColumn]=='Int' || is_subclass_of('Int', $extraFields[$this->sortColumn]))) {
user_error('Sort column '.$this->sortColumn.' must be an Int, column is of type '.$extraFields[$this->sortColumn], E_USER_ERROR);
exit;
}
}else {
//Find table containing the sort column
$table=false;
$class=$gridField->getModelClass();
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
if(!empty($db) && array_key_exists($sortColumn, $db)) {
$table=$class;
}else {
$classes=ClassInfo::ancestry($class, true);
foreach($classes as $class) {
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
if(!empty($db) && array_key_exists($sortColumn, $db)) {
$table=$class;
break;
}
}
}
if($table===false) {
user_error('Sort column '.$this->sortColumn.' could not be found in '.$gridField->getModelClass().'\'s ancestry', E_USER_ERROR);
exit;
}
$baseDataClass=ClassInfo::baseDataClass($gridField->getModelClass());
}
//Start transaction if supported
if(DB::getConn()->supportsTransactions()) {
DB::getConn()->transactionStart();
}
$idCondition=null;
if($this->append_to_top && !($list instanceof RelationList)) {
$idCondition='"ID" IN(\''.implode("','", $dataList->getIDList()).'\')';
}
if($this->append_to_top) {
$topIncremented=array();
}
foreach($list as $obj) {
if($many_many) {
if($this->append_to_top) {
//Upgrade all the records (including the last inserted from 0 to 1)
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = "' . $sortColumn .'"+1'
. ' WHERE "' . $parentField . '" = ' . $owner->ID . (!empty($topIncremented) ? ' AND "' . $componentField . '" NOT IN(\''.implode('\',\'', $topIncremented).'\')':''));
$topIncremented[]=$obj->ID;
}else {
//Append the last record to the bottom
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn .'" = ' . ($max + $i)
. ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
}
}else if($this->append_to_top) {
//Upgrade all the records (including the last inserted from 0 to 1)
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = "' . $sortColumn .'"+1'
. ' WHERE '.($list instanceof RelationList ? '"' . $list->foreignKey . '" = '. $owner->ID:$idCondition) . (!empty($topIncremented) ? ' AND "ID" NOT IN(\''.implode('\',\'', $topIncremented).'\')':''));
if($this->update_versioned_stage && class_exists($table) && Object::has_extension($table, 'Versioned')) {
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).'\')':''));
}
$topIncremented[]=$obj->ID;
}else {
//Append the last record to the bottom
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = ' . ($max + $i)
. ' WHERE "ID" = '. $obj->ID);
//LastEdited
DB::query('UPDATE "' . $baseDataClass
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
. ' WHERE "ID" = '. $obj->ID);
if($this->update_versioned_stage && class_exists($table) && Object::has_extension($table, 'Versioned')) {
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
. '" SET "' . $sortColumn . '" = ' . ($max + $i)
. ' WHERE "ID" = '. $obj->ID);
if(Object::has_extension($baseDataClass, 'Versioned')) {
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
. ' WHERE "ID" = '. $obj->ID);
}
}
}
$i++;
}
//Update LastEdited for affected records when using append to top on a many_many relationship
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).'\')');
if($this->update_versioned_stage && class_exists($table) && Object::has_extension($table, 'Versioned') && Object::has_extension($baseDataClass, 'Versioned')) {
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
. ' WHERE "ID" IN(\''.implode('\',\'', $topIncremented).'\')');
}
}
//End transaction if supported
if(DB::getConn()->supportsTransactions()) {
DB::getConn()->transactionEnd();
}
}
}
/**
* Return a list of the actions handled by this action provider.
* @param GridField $gridField Grid Field Reference
* @return Array Array with action identifier strings.
*/
public function getActions($gridField) {
return array('saveGridRowSort', 'sortableRowsToggle', 'sortToPage');
}
/**
* Handle an action on the given grid field.
* @param GridField $gridField Grid Field Reference
* @param String $actionName Action identifier, see {@link getActions()}.
* @param Array $arguments Arguments relevant for this
* @param Array $data All form data
*/
public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
$state = $gridField->State->GridFieldSortableRows;
if (!is_bool($state->sortableToggle)) {
$state->sortableToggle = false;
} else if ($state->sortableToggle == true) {
$gridField->getConfig()->removeComponentsByType('GridFieldFilterHeader');
$gridField->getConfig()->removeComponentsByType('GridFieldSortableHeader');
}
if ($actionName == 'savegridrowsort') {
return $this->saveGridRowSort($gridField, $data);
} else if ($actionName == 'sorttopage') {
return $this->sortToPage($gridField, $data);
}
}
/**
* Handles saving of the row sort order
* @param GridField $gridField Grid Field Reference
* @param Array $data Data submitted in the request
*/
protected function saveGridRowSort(GridField $gridField, $data) {
$dataList = $gridField->getList();
if(class_exists('UnsavedRelationList') && $dataList instanceof UnsavedRelationList) { /** @var null|string */
user_error('Cannot sort an UnsavedRelationList', E_USER_ERROR); protected $custom_relation_name = null;
return;
} /** @var array */
protected $tableMap = [];
if(!singleton($gridField->getModelClass())->canEdit()){
throw new ValidationException(_t('GridFieldSortableRows.EditPermissionsFailure', "No edit permissions"),0); /**
} * @param string $sortColumn Column that should be used to update the sort information
* @param bool $disableSelection Disable selection on the GridField when dragging
if (empty($data['ItemIDs'])) { * @param string $updateVersionStage Name of the versioned stage to update this disabled by default unless this is set
user_error('No items to sort', E_USER_ERROR); * @param string $customRelationName Name of the relationship to use, if left null the name is determined from the GridField's name
} */
public function __construct($sortColumn, $disableSelection = true, $updateVersionStage = null, $customRelationName = null)
$className = $gridField->getModelClass(); {
$owner = $gridField->Form->getRecord(); $this->sortColumn = $sortColumn;
$items = clone $gridField->getList(); $this->disable_selection = $disableSelection;
$many_many = ($items instanceof ManyManyList); $this->update_versioned_stage = $updateVersionStage;
$sortColumn = $this->sortColumn; $this->custom_relation_name = $customRelationName;
$pageOffset = 0; }
if ($paginator = $gridField->getConfig()->getComponentsByType('GridFieldPaginator')->First()) { /**
$pageState = $gridField->State->GridFieldPaginator; * 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
if($pageState->currentPage && is_int($pageState->currentPage) && $pageState->currentPage>1) { * @return array Map where the keys are fragment names and the values are pieces of HTML to add to these fragments.
$pageOffset = $paginator->getItemsPerPage() * ($pageState->currentPage - 1); */
} public function getHTMLFragments($gridField)
} {
$dataList = $gridField->getList();
if ($many_many) { if (class_exists('UnsavedRelationList') && $dataList instanceof UnsavedRelationList) {
list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name:$gridField->getName())); return array();
}else { }
//Find table containing the sort column
$table=false; $state = $gridField->State->GridFieldSortableRows;
$class=$gridField->getModelClass(); if (!is_bool($state->sortableToggle)) {
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED); $state->sortableToggle = false;
if(!empty($db) && array_key_exists($sortColumn, $db)) { }
$table=$class;
}else { //Ensure user can edit
$classes=ClassInfo::ancestry($class, true); if (!singleton($gridField->getModelClass())->canEdit()) {
foreach($classes as $class) { return array();
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED); }
if(!empty($db) && array_key_exists($sortColumn, $db)) {
$table=$class;
break; //Sort order toggle
} $sortOrderToggle = GridField_FormAction::create(
} $gridField,
} 'sortablerows-toggle',
'sorttoggle',
if($table===false) { 'sortableRowsToggle',
user_error('Sort column '.$this->sortColumn.' could not be found in '.$gridField->getModelClass().'\'s ancestry', E_USER_ERROR); null
exit; )->addExtraClass('sortablerows-toggle');
}
$baseDataClass=ClassInfo::baseDataClass($gridField->getModelClass()); $sortOrderSave = GridField_FormAction::create(
} $gridField,
'sortablerows-savesort',
'savesort',
//Event to notify the Controller or owner DataObject before list sort 'saveGridRowSort',
if($owner && $owner instanceof DataObject && method_exists($owner, 'onBeforeGridFieldRowSort')) { null
$owner->onBeforeGridFieldRowSort(clone $items); )->addExtraClass('sortablerows-savesort');
}else if(Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onBeforeGridFieldRowSort')) {
Controller::curr()->onBeforeGridFieldRowSort(clone $items);
} //Sort to Page Action
$sortToPage = GridField_FormAction::create(
$gridField,
//Start transaction if supported 'sortablerows-sorttopage',
if(DB::getConn()->supportsTransactions()) { 'sorttopage',
DB::getConn()->transactionStart(); 'sortToPage',
} null
)->addExtraClass('sortablerows-sorttopage');
//Perform sorting
$ids = explode(',', $data['ItemIDs']); $data = array('SortableToggle' => $sortOrderToggle,
for($sort = 0;$sort<count($ids);$sort++) { 'SortOrderSave' => $sortOrderSave,
$id = intval($ids[$sort]); 'SortToPage' => $sortToPage,
if ($many_many) { 'Checked' => ($state->sortableToggle == true ? ' checked = "checked"' : ''),
DB::query('UPDATE "' . $table 'List' => $dataList);
. '" SET "' . $sortColumn.'" = ' . (($sort + 1) + $pageOffset)
. ' WHERE "' . $componentField . '" = ' . $id . ' AND "' . $parentField . '" = ' . $owner->ID); $forTemplate = new arrayData($data);
} else {
DB::query('UPDATE "' . $table //Inject Requirements
. '" SET "' . $sortColumn . '" = ' . (($sort + 1) + $pageOffset) $custom = Config::inst()->get(GridFieldSortableRows::class, 'Base');
. ' WHERE "ID" = '. $id); $base = $custom ?: SORTABLE_GRIDFIELD_BASE;
DB::query('UPDATE "' . $baseDataClass Requirements::css($base . '/css/GridFieldSortableRows.css');
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\'' Requirements::javascript($base . '/javascript/GridFieldSortableRows.js');
. ' WHERE "ID" = '. $id);
$args = array('Colspan' => count($gridField->getColumns()), 'ID' => $gridField->ID(), 'DisableSelection' => $this->disable_selection);
if($this->update_versioned_stage && class_exists($table) && Object::has_extension($table, 'Versioned')) {
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage $fragments = array('header' => $forTemplate->renderWith('SortableGridField\Forms\Includes\GridFieldSortableRows', $args));
. '" SET "' . $sortColumn . '" = ' . (($sort + 1) + $pageOffset)
. ' WHERE "ID" = '. $id); if ($gridField->getConfig()->getComponentByType(GridFieldPaginator::class)) {
$fragments['after'] = $forTemplate->renderWith('SortableGridField\Forms\Includes\GridFieldSortableRows_paginator');
if(Object::has_extension($baseDataClass, 'Versioned')) { }
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\'' return $fragments;
. ' WHERE "ID" = '. $id); }
}
} /**
} * Manipulate the datalist as needed by this grid modifier.
} * @param GridField $gridField Grid Field Reference
* @param SS_List|DataList $dataList Data List to adjust
* @return DataList Modified Data List
//End transaction if supported */
if(DB::getConn()->supportsTransactions()) { public function getManipulatedData(GridField $gridField, SS_List $dataList)
DB::getConn()->transactionEnd(); {
} //Detect and correct items with a sort column value of 0 (push to bottom)
$this->fixSortColumn($gridField, $dataList);
//Event to notify the Controller or owner DataObject after list sort
if($owner && $owner instanceof DataObject && method_exists($owner, 'onAfterGridFieldRowSort')) { $headerState = $gridField->State->GridFieldSortableHeader;
$owner->onAfterGridFieldRowSort(clone $items); $state = $gridField->State->GridFieldSortableRows;
}else if(Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onAfterGridFieldRowSort')) { if ((!is_bool($state->sortableToggle) || $state->sortableToggle === false) && $headerState && is_string($headerState->SortColumn) && is_string($headerState->SortDirection)) {
Controller::curr()->onAfterGridFieldRowSort(clone $items); return $dataList->sort($headerState->SortColumn, $headerState->SortDirection);
} }
}
if ($state->sortableToggle === true) {
/** $gridField->getConfig()->removeComponentsByType(GridFieldFilterHeader::class);
* Handles sorting across pages $gridField->getConfig()->removeComponentsByType(GridFieldSortableHeader::class);
* @param GridField $gridField Grid Field Reference }
* @param Array $data Data submitted in the request
*/ return $dataList->sort($this->sortColumn);
protected function sortToPage(GridField $gridField, $data) { }
if (!$paginator = $gridField->getConfig()->getComponentsByType('GridFieldPaginator')->First()) {
user_error('Paginator not detected', E_USER_ERROR); /**
} * Sets if new records should be appended to the top or the bottom of the list
* @param bool $value Boolean true to append to the top false to append to the bottom
if (empty($data['ItemID'])) { * @return GridFieldSortableRows Returns the current instance
user_error('No item to sort', E_USER_ERROR); */
} public function setAppendToTop($value)
{
if (empty($data['Target'])) { $this->append_to_top = $value;
user_error('No target page', E_USER_ERROR); return $this;
} }
/**
$className = $gridField->getModelClass(); * @param bool $value Boolean true to disable selection of table contents false to enable selection
$owner = $gridField->Form->getRecord(); * @return GridFieldSortableRows Returns the current instance
$items = clone $gridField->getList(); */
$many_many = ($items instanceof ManyManyList); public function setDisableSelection($value)
$sortColumn = $this->sortColumn; {
$targetItem = $items->byID(intval($data['ItemID'])); $this->disable_selection = $value;
return $this;
if (!$targetItem) { }
user_error('Target item not found', E_USER_ERROR);
} /**
* Sets the suffix of the versioned stage that should be updated along side the default stage
$currentPage = 1; * @param string $value Versioned Stage to update this is disabled by default unless this is set
* @return GridFieldSortableRows Returns the current instance
*/
$pageState = $gridField->State->GridFieldPaginator; public function setUpdateVersionedStage($value)
if($pageState->currentPage && $pageState->currentPage>1) { {
$currentPage = $pageState->currentPage; $this->update_versioned_stage = $value;
} return $this;
}
if ($many_many) { /**
list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name:$gridField->getName())); * 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
*/
if ($data['Target'] == 'previouspage') { public function setCustomRelationName($value)
$items = $items->limit($paginator->getItemsPerPage() + 1, ($paginator->getItemsPerPage() * ($currentPage - 1)) - 1); {
} else if ($data['Target'] == 'nextpage') { $this->custom_relation_name = $value;
$items = $items->limit($paginator->getItemsPerPage() + 1, $paginator->getItemsPerPage() * ($currentPage - 1)); return $this;
} else { }
user_error('Not implemented: '.$data['Target'], E_USER_ERROR);
} /**
* Detects and corrects items with a sort column value of 0, by appending them to the bottom of the list
$sortPositions = $items->column($sortColumn); * @param GridField $gridField Grid Field Reference
* @param SS_List|DataList $dataList Data List of items to be checked
*/
//Event to notify the Controller or owner DataObject before list sort protected function fixSortColumn($gridField, SS_List $dataList)
if($owner && $owner instanceof DataObject && method_exists($owner, 'onBeforeGridFieldPageSort')) { {
$owner->onBeforeGridFieldPageSort(clone $items); if ($dataList instanceof UnsavedRelationList) {
}else if(Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onBeforeGridFieldPageSort')) { return;
Controller::curr()->onBeforeGridFieldPageSort(clone $items); }
}
/** @var SS_List|DataList $list */
$list = clone $dataList;
//Find the sort column $list = $list->alterDataQuery(function ($query, SS_List $tmplist) {
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { /** @var DataQuery $query */
$table=false; $query->limit(array());
$classes=ClassInfo::ancestry($className, true); return $query;
foreach($classes as $class) { });
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
if(!empty($db) && array_key_exists($sortColumn, $db)) { $many_many = ($list instanceof ManyManyList);
$table=$class; if (!$many_many) {
break; $sng = singleton($gridField->getModelClass());
} $fieldType = $sng->config()->db[$this->sortColumn];
}
if (!$fieldType || !(strtolower($fieldType) == 'int' || is_subclass_of($fieldType, 'Int'))) {
if($table===false) { if (is_array($fieldType)) {
user_error('Sort column '.$this->sortColumn.' could not be found in '.$gridField->getModelClass().'\'s ancestry', E_USER_ERROR); user_error('Sort column ' . $this->sortColumn . ' could not be found in ' . $gridField->getModelClass() . '\'s ancestry', E_USER_ERROR);
exit; } else {
} user_error('Sort column ' . $this->sortColumn . ' must be an Int, column is of type ' . $fieldType, E_USER_ERROR);
} }
exit;
//Start transaction if supported }
if(DB::getConn()->supportsTransactions()) { }
DB::getConn()->transactionStart();
} $max = $list->Max($this->sortColumn);
$list = $list->filter($this->sortColumn, 0)->sort("Created,ID");
if($data['Target']=='previouspage') { if ($list->Count() > 0) {
if ($many_many) { $owner = $gridField->getForm()->getRecord();
DB::query('UPDATE "' . $table $sortColumn = $this->sortColumn;
. '" SET "' . $sortColumn.'" = ' . $sortPositions[0] $i = 1;
. ' WHERE "' . $componentField . '" = ' . $targetItem->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
} else { if ($many_many) {
$targetItem->$sortColumn = $sortPositions[0]; list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name : $gridField->getName()));
$targetItem->write();
/** @var DataObject $table */
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { $table = $this->mapTableNameAndReturn($table);
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
. '" SET "' . $sortColumn.'" = ' . $sortPositions[0] $extraFields = $owner->many_many_extraFields((!empty($this->custom_relation_name) ? $this->custom_relation_name : $gridField->getName()));
. ' WHERE "ID" = ' . $targetItem->ID);
} 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 . ' must be an Int, column is of type ' . $extraFields[$this->sortColumn], E_USER_ERROR);
exit;
}
$i = 1; } else {
foreach ($items as $obj) { //Find table containing the sort column
if ($obj->ID == $targetItem->ID) { $table = false;
continue; $class = $gridField->getModelClass();
}
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
if (!empty($db) && array_key_exists($sortColumn, $db)) {
if ($many_many) { $table = $this->mapTableNameAndReturn($class);
DB::query('UPDATE "' . $table } else {
. '" SET "' . $sortColumn.'" = ' . $sortPositions[$i] $classes = ClassInfo::ancestry($class, true);
. ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID); foreach ($classes as $class) {
} else { $db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
$obj->$sortColumn = $sortPositions[$i]; if (!empty($db) && array_key_exists($sortColumn, $db)) {
$obj->write(); $table = $this->mapTableNameAndReturn($class);
break;
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { }
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage }
. '" SET "' . $sortColumn.'" = ' . $sortPositions[$i] }
. ' WHERE "ID" = ' . $obj->ID);
} if ($table === false) {
} user_error('Sort column ' . $this->sortColumn . ' could not be found in ' . $gridField->getModelClass() . '\'s ancestry', E_USER_ERROR);
exit;
$i++; }
}
} else { $baseDataClass = DataObject::getSchema()->baseDataClass($gridField->getModelClass());
if ($many_many) { $baseDataClass = $this->mapTableNameAndReturn($baseDataClass);
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn.'" = ' . $sortPositions[count($sortPositions) - 1] }
. ' WHERE "' . $componentField . '" = ' . $targetItem->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
} else {
$targetItem->$sortColumn = $sortPositions[count($sortPositions) - 1]; //Start transaction if supported
$targetItem->write(); if (DB::get_conn()->supportsTransactions()) {
DB::get_conn()->transactionStart();
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { }
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
. '" SET "' . $sortColumn.'" = ' . $sortPositions[count($sortPositions) - 1] $idCondition = null;
. ' WHERE "ID" = ' . $targetItem->ID); if ($this->append_to_top && !($list instanceof RelationList)) {
} $idCondition = '"ID" IN(\'' . implode("','", $dataList->getIDList()) . '\')';
} }
if ($this->append_to_top) {
$i = 0; $topIncremented = array();
foreach ($items as $obj) { }
if ($obj->ID == $targetItem->ID) {
continue; foreach ($list as $obj) {
} if ($many_many) {
if ($this->append_to_top) {
//Upgrade all the records (including the last inserted from 0 to 1)
if ($many_many) { DB::query('UPDATE "' . $table
DB::query('UPDATE "' . $table . '" SET "' . $sortColumn . '" = "' . $sortColumn . '"+1'
. '" SET "' . $sortColumn.'" = ' . $sortPositions[$i] . ' WHERE "' . $parentField . '" = ' . $owner->ID . (!empty($topIncremented) ? ' AND "' . $componentField . '" NOT IN(\'' . implode('\',\'', $topIncremented) . '\')' : ''));
. ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
} else { $topIncremented[] = $obj->ID;
$obj->$sortColumn = $sortPositions[$i]; } else {
$obj->write(); //Append the last record to the bottom
DB::query('UPDATE "' . $table
if($this->update_versioned_stage && Object::has_extension($className, 'Versioned')) { . '" SET "' . $sortColumn . '" = ' . ($max + $i)
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage . ' WHERE "' . $componentField . '" = ' . $obj->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
. '" SET "' . $sortColumn.'" = ' . $sortPositions[$i] }
. ' WHERE "ID" = ' . $obj->ID); } else if ($this->append_to_top) {
} //Upgrade all the records (including the last inserted from 0 to 1)
} DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = "' . $sortColumn . '"+1'
$i++; . ' WHERE ' . ($list instanceof RelationList ? '"' . $list->foreignKey . '" = ' . $owner->ID : $idCondition) . (!empty($topIncremented) ? ' AND "ID" NOT 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 . '" = "' . $sortColumn . '"+1'
//End transaction if supported . ' WHERE ' . ($list instanceof RelationList ? '"' . $list->foreignKey . '" = ' . $owner->ID : $idCondition) . (!empty($topIncremented) ? ' AND "ID" NOT IN(\'' . implode('\',\'', $topIncremented) . '\')' : ''));
if(DB::getConn()->supportsTransactions()) { }
DB::getConn()->transactionEnd();
} $topIncremented[] = $obj->ID;
} else {
//Append the last record to the bottom
//Event to notify the Controller or owner DataObject after list sort DB::query('UPDATE "' . $table
if($owner && $owner instanceof DataObject && method_exists($owner, 'onAfterGridFieldPageSort')) { . '" SET "' . $sortColumn . '" = ' . ($max + $i)
$owner->onAfterGridFieldPageSort(clone $items); . ' WHERE "ID" = ' . $obj->ID);
}else if(Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onAfterGridFieldPageSort')) { //LastEdited
Controller::curr()->onAfterGridFieldPageSort(clone $items); DB::query('UPDATE "' . $baseDataClass
} . '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
} . ' 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 . '" = ' . ($max + $i)
. ' WHERE "ID" = ' . $obj->ID);
if ($this->hasVersionedExtension($this->tableMap[$baseDataClass])) {
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
. ' WHERE "ID" = ' . $obj->ID);
}
}
}
$i++;
}
//Update LastEdited for affected records when using append to top on a many_many relationship
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) . '\')');
if ($this->update_versioned_stage && class_exists($this->tableMap[$table]) && $this->hasVersionedExtension($this->tableMap[$table]) && $this->hasVersionedExtension($this->tableMap[$baseDataClass])) {
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
. ' WHERE "ID" IN(\'' . implode('\',\'', $topIncremented) . '\')');
}
}
//End transaction if supported
if (DB::get_conn()->supportsTransactions()) {
DB::get_conn()->transactionEnd();
}
}
}
/**
* Return a list of the actions handled by this action provider.
* @param GridField $gridField Grid Field Reference
* @return array array with action identifier strings.
*/
public function getActions($gridField)
{
return array('saveGridRowSort', 'sortableRowsToggle', 'sortToPage');
}
/**
* Handle an action on the given grid field.
* @param GridField $gridField Grid Field Reference
* @param String $actionName Action identifier, see {@link getActions()}.
* @param array $arguments Arguments relevant for this
* @param array $data All form data
*/
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
$state = $gridField->State->GridFieldSortableRows;
if (!is_bool($state->sortableToggle)) {
$state->sortableToggle = false;
} else if ($state->sortableToggle == true) {
$gridField->getConfig()->removeComponentsByType(GridFieldFilterHeader::class);
$gridField->getConfig()->removeComponentsByType(GridFieldSortableHeader::class);
}
if ($actionName == 'savegridrowsort') {
return $this->saveGridRowSort($gridField, $data);
} else if ($actionName == 'sorttopage') {
return $this->sortToPage($gridField, $data);
}
}
/**
* Handles saving of the row sort order
* @param GridField $gridField Grid Field Reference
* @param array $data Data submitted in the request
* @throws ValidationException If user has no edit permissions
*/
protected function saveGridRowSort(GridField $gridField, $data)
{
$dataList = $gridField->getList();
if ($dataList instanceof UnsavedRelationList) {
user_error('Cannot sort an UnsavedRelationList', E_USER_ERROR);
return;
}
if (!singleton($gridField->getModelClass())->canEdit()) {
throw new ValidationException(_t('GridFieldSortableRows.EditPermissionsFailure', "No edit permissions"), 0);
}
if (empty($data['ItemIDs'])) {
user_error('No items to sort', E_USER_ERROR);
}
$className = $gridField->getModelClass();
$owner = $gridField->Form->getRecord();
$items = clone $gridField->getList();
$many_many = ($items instanceof ManyManyList);
$sortColumn = $this->sortColumn;
$pageOffset = 0;
if ($paginator = $gridField->getConfig()->getComponentsByType(GridFieldPaginator::class)->First()) {
$pageState = $gridField->State->GridFieldPaginator;
if ($pageState->currentPage && is_int($pageState->currentPage) && $pageState->currentPage > 1) {
$pageOffset = $paginator->getItemsPerPage() * ($pageState->currentPage - 1);
}
}
if ($many_many) {
list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name : $gridField->getName()));
/** @var DataObject $table */
$table = $this->mapTableNameAndReturn($table);
} else {
//Find table containing the sort column
$table = false;
$class = $gridField->getModelClass();
$db = Config::inst()->get($class, "db", CONFIG::UNINHERITED);
if (!empty($db) && array_key_exists($sortColumn, $db)) {
$table = $this->mapTableNameAndReturn($class);
} else {
$classes = ClassInfo::ancestry($class, true);
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;
}
}
}
if ($table === false) {
user_error('Sort column ' . $this->sortColumn . ' could not be found in ' . $gridField->getModelClass() . '\'s ancestry', E_USER_ERROR);
exit;
}
$baseDataClass = DataObject::getSchema()->baseDataClass($gridField->getModelClass());
$baseDataClass = $this->mapTableNameAndReturn($baseDataClass);
}
//Event to notify the Controller or owner DataObject before list sort
if ($owner && $owner instanceof DataObject && method_exists($owner, 'onBeforeGridFieldRowSort')) {
$owner->onBeforeGridFieldRowSort(clone $items);
} else if (Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onBeforeGridFieldRowSort')) {
Controller::curr()->onBeforeGridFieldRowSort(clone $items);
}
//Start transaction if supported
if (DB::get_conn()->supportsTransactions()) {
DB::get_conn()->transactionStart();
}
//Perform sorting
$ids = explode(',', $data['ItemIDs']);
for ($sort = 0; $sort < count($ids); $sort++) {
$id = intval($ids[$sort]);
if ($many_many) {
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = ' . (($sort + 1) + $pageOffset)
. ' WHERE "' . $componentField . '" = ' . $id . ' AND "' . $parentField . '" = ' . $owner->ID);
} else {
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = ' . (($sort + 1) + $pageOffset)
. ' WHERE "ID" = ' . $id);
DB::query('UPDATE "' . $baseDataClass
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
. ' WHERE "ID" = ' . $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 . '" = ' . (($sort + 1) + $pageOffset)
. ' WHERE "ID" = ' . $id);
if ($this->hasVersionedExtension($this->tableMap[$baseDataClass])) {
DB::query('UPDATE "' . $baseDataClass . '_' . $this->update_versioned_stage
. '" SET "LastEdited" = \'' . date('Y-m-d H:i:s') . '\''
. ' WHERE "ID" = ' . $id);
}
}
}
}
//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, 'onAfterGridFieldRowSort')) {
$owner->onAfterGridFieldRowSort(clone $items);
} else if (Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onAfterGridFieldRowSort')) {
Controller::curr()->onAfterGridFieldRowSort(clone $items);
}
}
/**
* Handles sorting across pages
* @param GridField $gridField Grid Field Reference
* @param array $data Data submitted in the request
*/
protected function sortToPage(GridField $gridField, $data)
{
if (!$paginator = $gridField->getConfig()->getComponentsByType(GridFieldPaginator::class)->First()) {
user_error('Paginator not detected', E_USER_ERROR);
}
if (empty($data['ItemID'])) {
user_error('No item to sort', E_USER_ERROR);
}
if (empty($data['Target'])) {
user_error('No target page', E_USER_ERROR);
}
/** @var Extensible $className */
$className = $gridField->getModelClass();
$owner = $gridField->Form->getRecord();
/** @var DataList $items */
$items = clone $gridField->getList();
$many_many = ($items instanceof ManyManyList);
$sortColumn = $this->sortColumn;
$targetItem = $items->byID(intval($data['ItemID']));
if (!$targetItem) {
user_error('Target item not found', E_USER_ERROR);
}
$currentPage = 1;
$pageState = $gridField->State->GridFieldPaginator;
if ($pageState->currentPage && $pageState->currentPage > 1) {
$currentPage = $pageState->currentPage;
}
if ($many_many) {
list($parentClass, $componentClass, $parentField, $componentField, $table) = $owner->many_many((!empty($this->custom_relation_name) ? $this->custom_relation_name : $gridField->getName()));
$table = $this->mapTableNameAndReturn($table);
}
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));
} else {
user_error('Not implemented: ' . $data['Target'], E_USER_ERROR);
}
$sortPositions = $items->column($sortColumn);
//Event to notify the Controller or owner DataObject before list sort
if ($owner && $owner instanceof DataObject && method_exists($owner, 'onBeforeGridFieldPageSort')) {
$owner->onBeforeGridFieldPageSort(clone $items);
} else if (Controller::has_curr() && Controller::curr() instanceof ModelAdmin && method_exists(Controller::curr(), 'onBeforeGridFieldPageSort')) {
Controller::curr()->onBeforeGridFieldPageSort(clone $items);
}
//Find the sort column
if ($this->update_versioned_stage && $this->hasVersionedExtension($className)) {
$table = false;
$classes = ClassInfo::ancestry($className, true);
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;
}
}
if ($table === false) {
user_error('Sort column ' . $this->sortColumn . ' could not be found in ' . $gridField->getModelClass() . '\'s ancestry', E_USER_ERROR);
exit;
}
}
//Start transaction if supported
if (DB::get_conn()->supportsTransactions()) {
DB::get_conn()->transactionStart();
}
if ($data['Target'] == 'previouspage') {
if ($many_many) {
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = ' . $sortPositions[0]
. ' WHERE "' . $componentField . '" = ' . $targetItem->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
} else {
$targetItem->$sortColumn = $sortPositions[0];
$targetItem->write();
if ($this->update_versioned_stage && $this->hasVersionedExtension($className)) {
DB::query('UPDATE "' . $table . '_' . $this->update_versioned_stage
. '" SET "' . $sortColumn . '" = ' . $sortPositions[0]
. ' WHERE "ID" = ' . $targetItem->ID);
}
}
$i = 1;
foreach ($items as $obj) {
if ($obj->ID == $targetItem->ID) {
continue;
}
if ($many_many) {
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++;
}
} else {
if ($many_many) {
DB::query('UPDATE "' . $table
. '" SET "' . $sortColumn . '" = ' . $sortPositions[count($sortPositions) - 1]
. ' WHERE "' . $componentField . '" = ' . $targetItem->ID . ' AND "' . $parentField . '" = ' . $owner->ID);
} else {
$targetItem->$sortColumn = $sortPositions[count($sortPositions) - 1];
$targetItem->write();
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);
}
}
$i = 0;
foreach ($items as $obj) {
if ($obj->ID == $targetItem->ID) {
continue;
}
if ($many_many) {
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) : $tableName;
$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', use SilverStripe\Control\Controller;
'GridFieldAction_SortOrder_VPlayer', use SilverStripe\Control\HTTPRequest;
'GridFieldAction_SortOrder_TestParent', use SilverStripe\Control\Session;
'GridFieldAction_SortOrder_BaseObject', use SilverStripe\Dev\SapphireTest;
'GridFieldAction_SortOrder_ChildObject' use SilverStripe\Dev\TestOnly;
); use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
public function testAutoSort() { use SilverStripe\Forms\GridField\GridField;
if(Member::currentUser()) { Member::currentUser()->logOut(); } use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\ORM\DataList;
$list = GridFieldAction_SortOrder_Player::get(); use SilverStripe\ORM\DataObject;
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder')); use SilverStripe\ORM\DB;
$gridField = new GridField('testfield', 'testfield', $list, $config); use SilverStripe\Security\Member;
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList()); use SilverStripe\Versioned\Versioned;
use UndefinedOffset\SortableGridField\Forms\GridFieldSortableRows;
$stateID = 'testGridStateActionField';
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())); * Class GridFieldSortableRowsAutoSortTest
$gridField->gridFieldAlterAction(array('StateID'=>$stateID), $form, $request); *
* @package SortableGridField\Tests
//Insure sort ran */
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run'); class GridFieldSortableRowsAutoSortTest extends SapphireTest
{
/** @var string */
//Check for duplicates (there shouldn't be any) public static $fixture_file = 'sortablegridfield/tests/forms/GridFieldSortableRowsAutoSortTest.yml';
$count=$list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); /** @var array */
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected'); protected static $extra_dataobjects = array(
} GridFieldAction_SortOrder_Player::class,
GridFieldAction_SortOrder_VPlayer::class,
public function testAppendToTopAutoSort() { GridFieldAction_SortOrder_TestParent::class,
if(Member::currentUser()) { Member::currentUser()->logOut(); } GridFieldAction_SortOrder_BaseObject::class,
GridFieldAction_SortOrder_ChildObject::class
$list = GridFieldAction_SortOrder_Player::get(); );
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
$gridField = new GridField('testfield', 'testfield', $list, $config); public function testAutoSort()
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList()); {
if (Member::currentUser()) {
$gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setAppendToTop(true); Member::currentUser()->logOut();
}
$this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not have run');
$list = GridFieldAction_SortOrder_Player::get();
$stateID = 'testGridStateActionField'; $config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortableRowsToggle', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); $gridField = new GridField('testfield', 'testfield', $list, $config);
$request = new SS_HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $form->getSecurityToken()->getName()=>$form->getSecurityToken()->getValue())); $form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($gridField)), new FieldList());
$gridField->gridFieldAlterAction(array('StateID'=>$stateID), $form, $request);
$stateID = 'testGridStateActionField';
//Insure sort ran Session::set($stateID, array('grid' => '', 'actionName' => 'sortableRowsToggle', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run'); $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);
//Check for duplicates (there shouldn't be any) //Insure sort ran
$count=$list->Count(); $this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run');
$indexes=count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected');
} //Check for duplicates (there shouldn't be any)
$count = $list->Count();
public function testAutoSortVersioned() { $indexes = count(array_unique($list->column('SortOrder')));
if(Member::currentUser()) { Member::currentUser()->logOut(); } $this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected');
}
//Force versioned to reset
Versioned::reset(); public function testAppendToTopAutoSort()
{
$list = GridFieldAction_SortOrder_VPlayer::get(); if (Member::currentUser()) {
Member::currentUser()->logOut();
//Publish all records }
foreach($list as $item) {
$item->publish('Stage', 'Live'); $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());
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder', true, 'Live'));
$gridField = new GridField('testfield', 'testfield', $list, $config); /** @var GridFieldSortableRows $sortableRows */
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList()); $sortableRows = $gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$sortableRows->setAppendToTop(true);
$stateID = 'testGridStateActionField';
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortableRowsToggle', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); $this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not have run');
$request = new SS_HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $form->getSecurityToken()->getName()=>$form->getSecurityToken()->getValue()));
$gridField->gridFieldAlterAction(array('StateID'=>$stateID), $form, $request); $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()));
//Insure sort ran $gridField->gridFieldAlterAction(array('StateID' => $stateID), $form, $request);
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Stage"');
//Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run');
//Check for duplicates (there shouldn't be any)
$count=$list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); //Check for duplicates (there shouldn't be any)
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected on Versioned stage "Stage"'); $count = $list->Count();
$indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected');
//Force versioned over to Live stage }
Versioned::reading_stage('Live');
public function testAutoSortVersioned()
//Get live instance {
$obj=Versioned::get_one_by_stage('GridFieldAction_SortOrder_VPlayer', 'Live', '"ID"='.$list->last()->ID); if (Member::currentUser()) {
Member::currentUser()->logOut();
//Insure sort ran }
$this->assertEquals(3, $obj->SortOrder, 'Auto sort should have run on Versioned stage "Live"');
//Force versioned to reset
Versioned::reset();
//Check for duplicates (there shouldn't be any)
$list=Versioned::get_by_stage('GridFieldAction_SortOrder_VPlayer', 'Live'); $list = GridFieldAction_SortOrder_VPlayer::get();
$count=$list->Count();
$indexes=count(array_unique($list->column('SortOrder'))); //Publish all records
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected on Versioned stage "Live"'); foreach ($list as $item) {
} $item->publish('Stage', 'Live');
}
public function testAppendToTopAutoSortVersioned() {
if(Member::currentUser()) { Member::currentUser()->logOut(); }
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder', true, 'Live'));
//Force versioned to reset $gridField = new GridField('testfield', 'testfield', $list, $config);
Versioned::reset(); $form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($gridField)), new FieldList());
$list = GridFieldAction_SortOrder_VPlayer::get(); $stateID = 'testGridStateActionField';
Session::set($stateID, array('grid' => '', 'actionName' => 'sortableRowsToggle', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
//Publish all records $request = new HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $form->getSecurityToken()->getName() => $form->getSecurityToken()->getValue()));
foreach($list as $item) { $gridField->gridFieldAlterAction(array('StateID' => $stateID), $form, $request);
$item->publish('Stage', 'Live');
}
//Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Stage"');
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder', true, 'Live'));
$gridField = new GridField('testfield', 'testfield', $list, $config);
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList()); //Check for duplicates (there shouldn't be any)
$count = $list->Count();
$gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setAppendToTop(true); $indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected on Versioned stage "Stage"');
$this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not have run on Versioned stage "Stage"');
$stateID = 'testGridStateActionField'; //Force versioned over to Live stage
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortableRowsToggle', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); Versioned::set_reading_mode('Live');
$request = new SS_HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $form->getSecurityToken()->getName()=>$form->getSecurityToken()->getValue()));
$gridField->gridFieldAlterAction(array('StateID'=>$stateID), $form, $request); //Get live instance
$obj = Versioned::get_one_by_stage(GridFieldAction_SortOrder_VPlayer::class, 'Live', '"ID"=' . $list->last()->ID);
//Insure sort ran //Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Stage"'); $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)
$count=$list->Count(); $list = Versioned::get_by_stage(GridFieldAction_SortOrder_VPlayer::class, 'Live');
$indexes=count(array_unique($list->column('SortOrder'))); $count = $list->Count();
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected on Versioned stage "Stage"'); $indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected on Versioned stage "Live"');
}
//Force versioned over to Live stage
Versioned::reading_stage('Live'); public function testAppendToTopAutoSortVersioned()
{
//Insure sort ran if (Member::currentUser()) {
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Live"'); Member::currentUser()->logOut();
}
//Check for duplicates (there shouldn't be any) //Force versioned to reset
$count=$list->Count(); Versioned::reset();
$indexes=count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count-$indexes, 'Duplicate indexes detected on Versioned stage "Live"'); $list = GridFieldAction_SortOrder_VPlayer::get();
}
//Publish all records
public function testAppendToTopAutoSortChild() { foreach ($list as $item) {
if(Member::currentUser()) { Member::currentUser()->logOut(); } $item->publish('Stage', 'Live');
}
//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')).'\'');
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder', true, 'Live'));
$parent = GridFieldAction_SortOrder_TestParent::get()->first(); $gridField = new GridField('testfield', 'testfield', $list, $config);
$list = $parent->TestRelation(); $form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($gridField)), new FieldList());
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
$gridField = new GridField('testfield', 'testfield', $list, $config); /** @var GridFieldSortableRows $sortableRows */
$form = new Form(new Controller(), 'mockform', new FieldList(array($gridField)), new FieldList()); $sortableRows = $gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$form->loadDataFrom($parent); $sortableRows->setAppendToTop(true);
$gridField->getConfig()->getComponentByType('GridFieldSortableRows')->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'); $stateID = 'testGridStateActionField';
Session::set($stateID, array('grid' => '', 'actionName' => 'sortableRowsToggle', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
$stateID = 'testGridStateActionField'; $request = new HTTPRequest('POST', 'url', array(), array('action_gridFieldAlterAction?StateID=' . $stateID => true, $form->getSecurityToken()->getName() => $form->getSecurityToken()->getValue()));
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortableRowsToggle', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); $gridField->gridFieldAlterAction(array('StateID' => $stateID), $form, $request);
$request = new SS_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
//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');
//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');
//Force versioned over to Live stage
//Make sure the last edited is today for all records Versioned::set_reading_mode('Live');
$this->assertEquals(3, $list->filter('LastEdited:GreaterThan', date('Y-m-d 00:00:00'))->count());
} //Insure sort ran
$this->assertEquals(3, $list->last()->SortOrder, 'Auto sort should have run on Versioned stage "Live"');
//Check for duplicates (there shouldn't be any)
$count = $list->Count();
$indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected on Versioned stage "Live"');
}
public function testAppendToTopAutoSortChild()
{
if (Member::currentUser()) {
Member::currentUser()->logOut();
}
//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')) . '\'');
/** @var GridFieldAction_SortOrder_TestParent $parent */
$parent = GridFieldAction_SortOrder_TestParent::get()->first();
/** @var DataList $list */
$list = $parent->TestRelation();
$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);
/** @var GridFieldSortableRows $sortableRows */
$sortableRows = $gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$sortableRows->setAppendToTop(true);
$this->assertEquals(0, $list->last()->SortOrder, 'Auto sort should not 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)
$count = $list->Count();
$indexes = count(array_unique($list->column('SortOrder')));
$this->assertEquals(0, $count - $indexes, 'Duplicate indexes detected');
//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());
}
} }
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
static $default_sort='SortOrder'; */
class GridFieldAction_SortOrder_Player extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_Player';
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
static $default_sort = 'SortOrder'; */
class GridFieldAction_SortOrder_VPlayer extends DataObject implements TestOnly
static $extensions=array( {
"Versioned('Stage', 'Live')" private static $table_name = 'GridFieldAction_SortOrder_VPlayer';
);
private static $db = array(
'Name' => 'Varchar',
'SortOrder' => 'Int'
);
private static $default_sort = 'SortOrder';
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
static $has_many = array( * @method GridFieldAction_SortOrder_ChildObject TestRelation
'TestRelation' => 'GridFieldAction_SortOrder_ChildObject' */
); class GridFieldAction_SortOrder_TestParent extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_TestParent';
private static $db = array(
'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
static $has_one = array( * @method GridFieldAction_SortOrder_TestParent Parent
'Parent'=>'GridFieldAction_SortOrder_TestParent' */
); class GridFieldAction_SortOrder_ChildObject extends GridFieldAction_SortOrder_BaseObject implements TestOnly
{
static $default_sort='SortOrder'; private static $table_name = 'GridFieldAction_SortOrder_ChildObject';
private static $db = array(
'SortOrder' => 'Int'
);
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 */
protected $gridField;
/** @var Form */
protected $form;
/** @var string */
public static $fixture_file = 'GridFieldSortableRowsPageTest.yml';
/** @var array */ use SilverStripe\Control\Controller;
protected $extraDataObjects = array('GridFieldAction_PageSortOrder_Team', 'GridFieldAction_PageSortOrder_VTeam'); use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\Session;
public function setUp() { use SilverStripe\Dev\SapphireTest;
parent::setUp(); use SilverStripe\Dev\TestOnly;
$this->list = GridFieldAction_PageSortOrder_Team::get(); use SilverStripe\Forms\FieldList;
$config = GridFieldConfig_Base::create(5)->addComponent(new GridFieldSortableRows('SortOrder')); use SilverStripe\Forms\Form;
$this->gridField = new GridField('testfield', 'testfield', $this->list, $config); use SilverStripe\Forms\GridField\GridField;
$this->form = new Form(new Controller(), 'mockform', new FieldList(array($this->gridField)), new FieldList()); use SilverStripe\Forms\GridField\GridFieldConfig_Base;
} use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject;
public function testSortToNextPage() { use SilverStripe\Versioned\Versioned;
$this->gridField->State->GridFieldPaginator->currentPage=1; use UndefinedOffset\SortableGridField\Forms\GridFieldSortableRows;
/**
$team3 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team3'); * Class GridFieldSortableRowsPageTest
*
$this->logInWithPermission('ADMIN'); * @package SortableGridField\Tests
$stateID = 'testGridStateActionField'; */
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortToPage', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true), 'GridFieldPaginator'=>array('currentPage'=>1)))); class GridFieldSortableRowsPageTest extends SapphireTest
$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); /** @var ArrayList */
protected $list;
$team6 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team6'); /** @var GridField */
$this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page'); protected $gridField;
$team3 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team3'); /** @var Form */
$this->assertEquals(6, $team3->SortOrder, 'Team 3 Should have moved to the top of the second page'); protected $form;
}
/** @var string */
public function testSortToPrevPage() { public static $fixture_file = 'sortablegridfield/tests/forms/GridFieldSortableRowsPageTest.yml';
$this->gridField->State->GridFieldPaginator->currentPage=2;
/** @var array */
protected static $extra_dataobjects = array(
$team7 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team7'); GridFieldAction_PageSortOrder_Team::class,
GridFieldAction_PageSortOrder_VTeam::class
$this->logInWithPermission('ADMIN'); );
$stateID = 'testGridStateActionField';
Session::set($stateID, array('grid'=>'', 'actionName'=>'sortToPage', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true), 'GridFieldPaginator'=>array('currentPage'=>1)))); public function setUp()
$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); parent::setUp();
$this->list = GridFieldAction_PageSortOrder_Team::get();
$config = GridFieldConfig_Base::create(5)->addComponent(new GridFieldSortableRows('SortOrder'));
$team7 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team7'); $this->gridField = new GridField('testfield', 'testfield', $this->list, $config);
$this->assertEquals(5, $team7->SortOrder, 'Team 7 Should have moved to the bottom of the first page'); $this->form = new Form(new SortableGridField_DummyController(), 'mockform', FieldList::create(array($this->gridField)), FieldList::create());
}
$team5 = $this->objFromFixture('GridFieldAction_PageSortOrder_Team', 'team5');
$this->assertEquals(6, $team5->SortOrder, 'Team 5 Should have moved to the top of the second page'); public function testSortToNextPage()
} {
$this->gridField->State->GridFieldPaginator->currentPage = 1;
public function testSortToNextPageVersioned() {
//Force versioned to reset $team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team', 'team3');
Versioned::reset();
$this->logInWithPermission('ADMIN');
$list=GridFieldAction_PageSortOrder_VTeam::get(); $stateID = 'testGridStateActionField';
$this->gridField->setList($list); Session::set($stateID, array('grid' => '', 'actionName' => 'sortToPage', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true), 'GridFieldPaginator' => array('currentPage' => 1))));
$this->gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setUpdateVersionedStage('Live'); $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->State->GridFieldPaginator->currentPage=1; $this->gridField->gridFieldAlterAction(array('StateID' => $stateID), $this->form, $request);
//Publish all records $team6 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team', 'team6');
foreach($list as $item) { $this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page');
$item->publish('Stage', 'Live');
} $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');
}
$team3 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team3');
public function testSortToPrevPage()
$this->logInWithPermission('ADMIN'); {
$stateID = 'testGridStateActionField'; $this->gridField->State->GridFieldPaginator->currentPage = 2;
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())); $team7 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_Team', 'team7');
$this->gridField->gridFieldAlterAction(array('StateID'=>$stateID), $this->form, $request);
$this->logInWithPermission('ADMIN');
$stateID = 'testGridStateActionField';
$team6 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team6'); Session::set($stateID, array('grid' => '', 'actionName' => 'sortToPage', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true), 'GridFieldPaginator' => array('currentPage' => 1))));
$this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page on Versioned stage "Stage"'); $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_VTeam', 'team3');
$this->assertEquals(6, $team3->SortOrder, 'Team 3 Should have moved to the top of the second page on Versioned stage "Stage"');
$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');
$list=Versioned::get_by_stage('GridFieldAction_PageSortOrder_VTeam', 'Live');
$team5 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\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"'); }
$team3 = $list->byID($team3->ID); public function testSortToNextPageVersioned()
$this->assertEquals(6, $team3->SortOrder, 'Team 3 Should have moved to the top of the second page on Versioned stage "Live"'); {
} //Force versioned to reset
Versioned::reset();
public function testSortToPrevPageVersioned() {
//Force versioned to reset $list = GridFieldAction_PageSortOrder_VTeam::get();
Versioned::reset(); $this->gridField->setList($list);
$list=GridFieldAction_PageSortOrder_VTeam::get(); /** @var GridFieldSortableRows $sortableGrid */
$this->gridField->setList($list); $sortableGrid = $this->gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$this->gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setUpdateVersionedStage('Live'); $sortableGrid->setUpdateVersionedStage('Live');
$this->gridField->State->GridFieldPaginator->currentPage=2; $this->gridField->State->GridFieldPaginator->currentPage = 1;
//Publish all records //Publish all records
foreach($list as $item) { foreach ($list as $item) {
$item->publish('Stage', 'Live'); $item->publish('Stage', 'Live');
} }
$team7 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team7'); $team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam', 'team3');
$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'=>$team7->ID, 'Target'=>'previouspage'), array('action_gridFieldAlterAction?StateID='.$stateID=>true, $this->form->getSecurityToken()->getName()=>$this->form->getSecurityToken()->getValue())); $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); $this->gridField->gridFieldAlterAction(array('StateID' => $stateID), $this->form, $request);
$team7 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team7'); $team6 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam', 'team6');
$this->assertEquals(5, $team7->SortOrder, 'Team 7 Should have moved to the bottom of the first page on Versioned stage "Stage"'); $this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page on Versioned stage "Stage"');
$team5 = $this->objFromFixture('GridFieldAction_PageSortOrder_VTeam', 'team5'); $team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_PageSortOrder_VTeam', 'team3');
$this->assertEquals(6, $team5->SortOrder, 'Team 5 Should have moved to the top of the second page on Versioned stage "Stage"'); $this->assertEquals(6, $team3->SortOrder, 'Team 3 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');
$team7 = $list->byID($team7->ID); $team6 = $list->byID($team6->ID);
$this->assertEquals(5, $team7->SortOrder, 'Team 7 Should have moved to the bottom of the first page on Versioned stage "Live"'); $this->assertEquals(5, $team6->SortOrder, 'Team 6 Should have moved to the bottom of the first page on Versioned stage "Live"');
$team5 = $list->byID($team5->ID); $team3 = $list->byID($team3->ID);
$this->assertEquals(6, $team5->SortOrder, 'Team 5 Should have moved to the top of the second page on Versioned stage "Live"'); $this->assertEquals(6, $team3->SortOrder, 'Team 3 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);
/** @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');
}
$team7 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\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 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('UndefinedOffset\SortableGridField\Tests\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('UndefinedOffset\SortableGridField\Tests\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::class, '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
static $default_sort='SortOrder'; */
class GridFieldAction_PageSortOrder_Team extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_PageSortOrder_Team';
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
static $default_sort='SortOrder'; */
class GridFieldAction_PageSortOrder_VTeam extends DataObject implements TestOnly
static $extensions=array( {
"Versioned('Stage', 'Live')" private static $table_name = 'GridFieldAction_PageSortOrder_VTeam';
);
private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar',
'SortOrder' => 'Int'
);
private static $default_sort = 'SortOrder';
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 */
protected $gridField;
/** @var Form */
protected $form;
/** @var string */
public static $fixture_file = 'GridFieldSortableRowsTest.yml';
/** @var array */ use SilverStripe\Control\HTTPRequest;
protected $extraDataObjects = array('GridFieldAction_SortOrder_Team', 'GridFieldAction_SortOrder_VTeam'); use SilverStripe\Control\Session;
use SilverStripe\Dev\SapphireTest;
public function setUp() { use SilverStripe\Dev\TestOnly;
parent::setUp(); use SilverStripe\Forms\FieldList;
$this->list = GridFieldAction_SortOrder_Team::get(); use SilverStripe\Forms\Form;
$config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder')); use SilverStripe\Forms\GridField\GridField;
$this->gridField = new GridField('testfield', 'testfield', $this->list, $config); use SilverStripe\Forms\GridField\GridFieldConfig;
$this->form = new Form(new Controller(), 'mockform', new FieldList(array($this->gridField)), new FieldList()); use SilverStripe\ORM\ArrayList;
} use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\ValidationException;
public function testSortActionWithoutCorrectPermission() { use SilverStripe\Security\Member;
if(Member::currentUser()) { Member::currentUser()->logOut(); } use SilverStripe\Versioned\Versioned;
$this->setExpectedException('ValidationException'); use UndefinedOffset\SortableGridField\Forms\GridFieldSortableRows;
$team1 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team1');
$team2 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team2'); class GridFieldSortableRowsTest extends SapphireTest
$team3 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team3'); {
/** @var ArrayList */
$stateID = 'testGridStateActionField'; protected $list;
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())); /** @var GridField */
$this->gridField->gridFieldAlterAction(array('StateID'=>$stateID), $this->form, $request); protected $gridField;
$this->assertEquals($team3->ID, $this->list->last()->ID, 'User should\'t be able to sort records without correct permissions.');
} /** @var Form */
protected $form;
public function testSortActionWithAdminPermission() {
$team1 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team1'); /** @var string */
$team2 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team2'); public static $fixture_file = 'sortablegridfield/tests/forms/GridFieldSortableRowsTest.yml';
$team3 = $this->objFromFixture('GridFieldAction_SortOrder_Team', 'team3');
$this->logInWithPermission('ADMIN'); /** @var array */
$stateID = 'testGridStateActionField'; protected static $extra_dataobjects = array(
Session::set($stateID, array('grid'=>'', 'actionName'=>'saveGridRowSort', 'args'=>array('GridFieldSortableRows'=>array('sortableToggle'=>true)))); GridFieldAction_SortOrder_Team::class,
$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())); GridFieldAction_SortOrder_VTeam::class
$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.');
} public function setUp()
{
public function testSortActionVersioned() { parent::setUp();
//Force versioned to reset $this->list = GridFieldAction_SortOrder_Team::get();
Versioned::reset(); $config = GridFieldConfig::create()->addComponent(new GridFieldSortableRows('SortOrder'));
$this->gridField = new GridField('testfield', 'testfield', $this->list, $config);
$list = GridFieldAction_SortOrder_VTeam::get(); $this->form = new Form(new SortableGridField_DummyController(), 'mockform', new FieldList(array($this->gridField)), new FieldList());
$this->gridField->setList($list); }
$this->gridField->getConfig()->getComponentByType('GridFieldSortableRows')->setUpdateVersionedStage('Live');
public function testSortActionWithoutCorrectPermission()
//Publish all records {
foreach($list as $item) { if (Member::currentUser()) {
$item->publish('Stage', 'Live'); Member::currentUser()->logOut();
} }
$this->setExpectedException(ValidationException::class);
$team1 = $this->objFromFixture('GridFieldAction_SortOrder_VTeam', 'team1'); $team1 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team', 'team1');
$team2 = $this->objFromFixture('GridFieldAction_SortOrder_VTeam', 'team2'); $team2 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team', 'team2');
$team3 = $this->objFromFixture('GridFieldAction_SortOrder_VTeam', 'team3'); $team3 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_Team', 'team3');
$this->logInWithPermission('ADMIN'); $stateID = 'testGridStateActionField';
$stateID = 'testGridStateActionField'; Session::set($stateID, array('grid' => '', 'actionName' => 'saveGridRowSort', 'args' => array('GridFieldSortableRows' => array('sortableToggle' => true))));
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()));
$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->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.');
}
$this->assertEquals($team2->ID, $list->last()->ID, 'Sort should have happened on Versioned stage "Stage"');
public function testSortActionWithAdminPermission()
$list=Versioned::get_by_stage('GridFieldAction_SortOrder_VTeam', 'Live'); {
$this->assertEquals($team2->ID, $list->last()->ID, 'Sort should have happened on Versioned stage "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.');
}
public function testSortActionVersioned()
{
//Force versioned to reset
Versioned::reset();
$list = GridFieldAction_SortOrder_VTeam::get();
$this->gridField->setList($list);
/** @var GridFieldSortableRows $sortableGrid */
$sortableGrid = $this->gridField->getConfig()->getComponentByType(GridFieldSortableRows::class);
$sortableGrid->setUpdateVersionedStage('Live');
//Publish all records
foreach ($list as $item) {
$item->publish('Stage', 'Live');
}
$team1 = $this->objFromFixture('UndefinedOffset\SortableGridField\Tests\GridFieldAction_SortOrder_VTeam', 'team1');
$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
static $default_sort='SortOrder'; */
class GridFieldAction_SortOrder_Team extends DataObject implements TestOnly
{
private static $table_name = 'GridFieldAction_SortOrder_Team';
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
static $default_sort='SortOrder'; */
class GridFieldAction_SortOrder_VTeam extends DataObject implements TestOnly
static $extensions=array( {
"Versioned('Stage', 'Live')" private static $table_name = 'GridFieldAction_SortOrder_VTeam';
);
private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar',
'SortOrder' => 'Int'
);
private static $default_sort = 'SortOrder';
private static $extensions = array(
"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