| 1 | <?php |
||
| 2 | |||
| 3 | namespace LeKoala\CommonExtensions; |
||
| 4 | |||
| 5 | use SilverStripe\ORM\DataList; |
||
| 6 | use SilverStripe\ORM\DataObject; |
||
| 7 | use SilverStripe\Forms\FieldList; |
||
| 8 | use SilverStripe\ORM\DataExtension; |
||
| 9 | |||
| 10 | /** |
||
| 11 | * Make a DataObject sortable with GridFieldOrderableRows |
||
| 12 | * |
||
| 13 | * @property DataObject $owner |
||
| 14 | * @property int $Sort |
||
| 15 | */ |
||
| 16 | class SortableExtension extends DataExtension |
||
| 17 | { |
||
| 18 | private static $db = [ |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 19 | "Sort" => "Int", |
||
| 20 | ]; |
||
| 21 | private static $default_sort = 'Sort ASC'; |
||
|
0 ignored issues
–
show
|
|||
| 22 | |||
| 23 | public function updateCMSFields(FieldList $fields) |
||
| 24 | { |
||
| 25 | $fields->removeByName('Sort'); |
||
| 26 | } |
||
| 27 | |||
| 28 | public function onBeforeWrite() |
||
| 29 | { |
||
| 30 | if (!$this->owner->Sort) { |
||
| 31 | $this->owner->Sort = $this->owner->getNextSort(); |
||
| 32 | } |
||
| 33 | } |
||
| 34 | /** |
||
| 35 | * This allows you to define your own method if needed |
||
| 36 | * Like when you have page dependent data objects that shouldn't use a global sort |
||
| 37 | * Or if you want to sort by a given multiple to allow inserts later on |
||
| 38 | * @return int |
||
| 39 | */ |
||
| 40 | public function getNextSort() |
||
| 41 | { |
||
| 42 | $class = get_class($this->owner); |
||
| 43 | $max = (int) $class::get()->max('Sort'); |
||
| 44 | return $max + 1; |
||
| 45 | } |
||
| 46 | |||
| 47 | /** |
||
| 48 | * @param DataList $list |
||
| 49 | * @return DataObject |
||
| 50 | */ |
||
| 51 | public function PreviousInList($list) |
||
| 52 | { |
||
| 53 | return $list->where('Sort < ' . $this->owner->Sort)->sort('Sort DESC')->first(); |
||
| 54 | } |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @param DataList $list |
||
| 58 | * @return DataObject |
||
| 59 | */ |
||
| 60 | public function NextInList($list) |
||
| 61 | { |
||
| 62 | return $list->where('Sort > ' . $this->owner->Sort)->sort('Sort ASC')->first(); |
||
| 63 | } |
||
| 64 | } |
||
| 65 |