-
Notifications
You must be signed in to change notification settings - Fork 821
/
TreeDropdownField.php
802 lines (708 loc) · 23 KB
/
TreeDropdownField.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
<?php
namespace SilverStripe\Forms;
use SilverStripe\Assets\Folder;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Convert;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\Hierarchy\Hierarchy;
use SilverStripe\ORM\Hierarchy\MarkedSet;
use SilverStripe\View\ViewableData;
use Exception;
use InvalidArgumentException;
/**
* Dropdown-like field that allows you to select an item from a hierarchical
* AJAX-expandable tree.
*
* Creates a field which opens a dropdown (actually a div via javascript
* included for you) which contains a tree with the ability to select a singular
* item for the value of the field. This field has the ability to store one-to-one
* joins related to hierarchy or a hierarchy based filter.
*
* **Note:** your source object must use an implementation of hierarchy for this
* field to generate the tree correctly, e.g. {@link Group}, {@link SiteTree} etc.
*
* All operations are carried out through javascript and provides no fallback
* to non JS.
*
* <b>Usage</b>.
*
* <code>
* static $has_one = array(
* 'RightContent' => 'SiteTree'
* );
*
* function getCMSFields() {
* ...
* $treedropdownfield = new TreeDropdownField("RightContentID", "Choose a page to show on the right:", "SiteTree");
* ..
* }
* </code>
*
* This will generate a tree allowing the user to expand and contract subsections
* to find the appropriate page to save to the field.
*
* Caution: The form field does not include any JavaScript or CSS when used outside of the CMS context,
* since the required frontend dependencies are included through CMS bundling.
*
* @see TreeMultiselectField for the same implementation allowing multiple selections
* @see DropdownField for a simple dropdown field.
* @see CheckboxSetField for multiple selections through checkboxes.
* @see OptionsetField for single selections via radiobuttons.
*/
class TreeDropdownField extends FormField
{
protected $schemaDataType = self::SCHEMA_DATA_TYPE_SINGLESELECT;
/** @skipUpgrade */
protected $schemaComponent = 'TreeDropdownField';
private static $url_handlers = array(
'$Action!/$ID' => '$Action'
);
private static $allowed_actions = array(
'tree'
);
/**
* @var string
*/
protected $emptyString = null;
/**
* @var bool
*/
protected $hasEmptyDefault = false;
/**
* Class name for underlying object
*
* @var string
*/
protected $sourceObject = null;
/**
* Name of key field on underlying object
*
* @var string
*/
protected $keyField = null;
/**
* Name of lavel field on underlying object
*
* @var string
*/
protected $labelField = null;
/**
* Callback for filtering records
*
* @var callable
*/
protected $filterCallback = null;
/**
* Callback for marking record as disabled
*
* @var callable
*/
protected $disableCallback = null;
/**
* Callback for searching records. This callback takes the following arguments:
* - sourceObject Object class to search
* - labelField Label field
* - search Search text
*
* @var callable
*/
protected $searchCallback = null;
/**
* Filter for base record
*
* @var int
*/
protected $baseID = 0;
/**
* Default child method in Hierarchy->getChildrenAsUL
*
* @var string
*/
protected $childrenMethod = 'AllChildrenIncludingDeleted';
/**
* Default child counting method in Hierarchy->getChildrenAsUL
*
* @var string
*/
protected $numChildrenMethod = 'numChildren';
/**
* Current string value for search text to filter on
*
* @var string
*/
protected $search = null;
/**
* List of ids in current search result (keys are ids, values are true)
* This includes parents of search result children which may not be an actual result
*
* @var array
*/
protected $searchIds = [];
/**
* List of ids which matches the search result
* This excludes parents of search result children
*
* @var array
*/
protected $realSearchIds = [];
/**
* Determine if search should be shown
*
* @var bool
*/
protected $showSearch = false;
/**
* List of ids which have their search expanded (keys are ids, values are true)
*
* @var array
*/
protected $searchExpanded = [];
/**
* CAVEAT: for search to work properly $labelField must be a database field,
* or you need to setSearchFunction.
*
* @param string $name the field name
* @param string $title the field label
* @param string $sourceObject A DataObject class name with the {@link Hierarchy} extension.
* @param string $keyField to field on the source class to save as the
* field value (default ID).
* @param string $labelField the field name to show as the human-readable
* value on the tree (default Title).
* @param bool $showSearch enable the ability to search the tree by
* entering the text in the input field.
*/
public function __construct(
$name,
$title = null,
$sourceObject = null,
$keyField = 'ID',
$labelField = 'TreeTitle',
$showSearch = true
) {
if (!is_a($sourceObject, DataObject::class, true)) {
throw new InvalidArgumentException("SourceObject must be a DataObject subclass");
}
if (!DataObject::has_extension($sourceObject, Hierarchy::class)) {
throw new InvalidArgumentException("SourceObject must have Hierarchy extension");
}
$this->sourceObject = $sourceObject;
$this->keyField = $keyField;
$this->labelField = $labelField;
$this->showSearch = $showSearch;
// Extra settings for Folders
if (strcasecmp($sourceObject, Folder::class) === 0) {
$this->childrenMethod = 'ChildFolders';
$this->numChildrenMethod = 'numChildFolders';
}
$this->addExtraClass('single');
parent::__construct($name, $title);
}
/**
* Set the ID of the root node of the tree. This defaults to 0 - i.e.
* displays the whole tree.
*
* @param int $ID
* @return $this
*/
public function setTreeBaseID($ID)
{
$this->baseID = (int) $ID;
return $this;
}
/**
* Set a callback used to filter the values of the tree before
* displaying to the user.
*
* @param callback $callback
* @return $this
*/
public function setFilterFunction($callback)
{
if (!is_callable($callback, true)) {
throw new InvalidArgumentException('TreeDropdownField->setFilterCallback(): not passed a valid callback');
}
$this->filterCallback = $callback;
return $this;
}
/**
* Set a callback used to disable checkboxes for some items in the tree
*
* @param callback $callback
* @return $this
*/
public function setDisableFunction($callback)
{
if (!is_callable($callback, true)) {
throw new InvalidArgumentException('TreeDropdownField->setDisableFunction(): not passed a valid callback');
}
$this->disableCallback = $callback;
return $this;
}
/**
* Set a callback used to search the hierarchy globally, even before
* applying the filter.
*
* @param callback $callback
* @return $this
*/
public function setSearchFunction($callback)
{
if (!is_callable($callback, true)) {
throw new InvalidArgumentException('TreeDropdownField->setSearchFunction(): not passed a valid callback');
}
$this->searchCallback = $callback;
return $this;
}
/**
* Check if search is shown
*
* @return bool
*/
public function getShowSearch()
{
return $this->showSearch;
}
/**
* @param bool $bool
* @return $this
*/
public function setShowSearch($bool)
{
$this->showSearch = $bool;
return $this;
}
/**
* @param string $method The parameter to ChildrenMethod to use when calling Hierarchy->getChildrenAsUL in
* {@link Hierarchy}. The method specified determines the structure of the returned list. Use "ChildFolders"
* in place of the default to get a drop-down listing with only folders, i.e. not including the child elements in
* the currently selected folder. setNumChildrenMethod() should be used as well for proper functioning.
*
* See {@link Hierarchy} for a complete list of possible methods.
* @return $this
*/
public function setChildrenMethod($method)
{
$this->childrenMethod = $method;
return $this;
}
/**
* @param string $method The parameter to numChildrenMethod to use when calling Hierarchy->getChildrenAsUL in
* {@link Hierarchy}. Should be used in conjunction with setChildrenMethod().
*
* @return $this
*/
public function setNumChildrenMethod($method)
{
$this->numChildrenMethod = $method;
return $this;
}
/**
* @param array $properties
* @return string
*/
public function Field($properties = array())
{
$record = $this->Value() ? $this->objectForKey($this->Value()) : null;
if ($record instanceof ViewableData) {
$title = $record->obj($this->labelField)->forTemplate();
} elseif ($record) {
$title = Convert::raw2xml($record->{$this->labelField});
} else {
$title = $this->getEmptyString();
}
// TODO Implement for TreeMultiSelectField
$metadata = array(
'id' => $record ? $record->ID : null,
'ClassName' => $record ? $record->ClassName : $this->sourceObject
);
$properties = array_merge(
$properties,
array(
'Title' => $title,
'EmptyTitle' => $this->getEmptyString(),
'Metadata' => ($metadata) ? Convert::raw2json($metadata) : null,
)
);
return parent::Field($properties);
}
public function extraClass()
{
return implode(' ', array(parent::extraClass(), ($this->showSearch ? "searchable" : null)));
}
/**
* Get the whole tree of a part of the tree via an AJAX request.
*
* @param HTTPRequest $request
* @return HTTPResponse
* @throws Exception
*/
public function tree(HTTPRequest $request)
{
// Regular source specification
$isSubTree = false;
$this->search = $request->requestVar('search');
$flatlist = $request->requestVar('flatList');
$id = (is_numeric($request->latestParam('ID')))
? (int)$request->latestParam('ID')
: (int)$request->requestVar('ID');
// pre-process the tree - search needs to operate globally, not locally as marking filter does
if ($this->search) {
$this->populateIDs();
}
/** @var DataObject|Hierarchy $obj */
$obj = null;
if ($id && !$request->requestVar('forceFullTree')) {
$obj = DataObject::get_by_id($this->sourceObject, $id);
$isSubTree = true;
if (!$obj) {
throw new Exception(
"TreeDropdownField->tree(): the object #$id of type $this->sourceObject could not be found"
);
}
} else {
if ($this->baseID) {
$obj = DataObject::get_by_id($this->sourceObject, $this->baseID);
}
if (!$this->baseID || !$obj) {
$obj = DataObject::singleton($this->sourceObject);
}
}
// Create marking set
$markingSet = MarkedSet::create($obj, $this->childrenMethod, $this->numChildrenMethod, 30);
// Set filter on searched nodes
if ($this->filterCallback || $this->search) {
// Rely on filtering to limit tree
$markingSet->setMarkingFilterFunction(function ($node) {
return $this->filterMarking($node);
});
$markingSet->setLimitingEnabled(false);
}
// Begin marking
$markingSet->markPartialTree();
// Allow to pass values to be selected within the ajax request
$value = $request->requestVar('forceValue') ?: $this->value;
if ($value && ($values = preg_split('/,\s*/', $value))) {
foreach ($values as $value) {
if (!$value || $value == 'unchanged') {
continue;
}
$object = $this->objectForKey($value);
if (!$object) {
continue;
}
$markingSet->markToExpose($object);
}
}
// Set title formatter
$customised = function (DataObject $child) use ($isSubTree) {
return [
'name' => $this->getName(),
'id' => $child->obj($this->keyField),
'title' => $child->getTitle(),
'treetitle' => $child->obj($this->labelField),
'disabled' => $this->nodeIsDisabled($child),
'isSubTree' => $isSubTree
];
};
// Determine output format
if ($request->requestVar('format') === 'json') {
// Format JSON output
$json = $markingSet
->getChildrenAsArray($customised);
if ($flatlist) {
// format and filter $json here
$json['children'] = $this->flattenChildrenArray($json['children']);
}
return HTTPResponse::create()
->addHeader('Content-Type', 'application/json')
->setBody(json_encode($json));
} else {
// Return basic html
$html = $markingSet->renderChildren(
[self::class . '_HTML', 'type' => 'Includes'],
$customised
);
return HTTPResponse::create()
->addHeader('Content-Type', 'text/html')
->setBody($html);
}
}
/**
* Marking public function for the tree, which combines different filters sensibly.
* If a filter function has been set, that will be called. And if search text is set,
* filter on that too. Return true if all applicable conditions are true, false otherwise.
*
* @param DataObject $node
* @return bool
*/
public function filterMarking($node)
{
if ($this->filterCallback && !call_user_func($this->filterCallback, $node)) {
return false;
}
if ($this->search) {
return isset($this->searchIds[$node->ID]) && $this->searchIds[$node->ID] ? true : false;
}
return true;
}
/**
* Marking a specific node in the tree as disabled
* @param $node
* @return boolean
*/
public function nodeIsDisabled($node)
{
return ($this->disableCallback && call_user_func($this->disableCallback, $node));
}
/**
* @param string $field
* @return $this
*/
public function setLabelField($field)
{
$this->labelField = $field;
return $this;
}
/**
* @return String
*/
public function getLabelField()
{
return $this->labelField;
}
/**
* @param string $field
* @return $this
*/
public function setKeyField($field)
{
$this->keyField = $field;
return $this;
}
/**
* @return String
*/
public function getKeyField()
{
return $this->keyField;
}
/**
* @param string $class
* @return $this
*/
public function setSourceObject($class)
{
$this->sourceObject = $class;
return $this;
}
/**
* @return String
*/
public function getSourceObject()
{
return $this->sourceObject;
}
/**
* Flattens a given list of children array items, so the data is no longer
* structured in a hierarchy
*
* NOTE: uses {@link TreeDropdownField::$realSearchIds} to filter items by if there is a search
*
* @param array $children - the list of children, which could contain their own children
* @param array $parentTitles - a list of parent titles, which we use to construct the contextString
* @return array - flattened list of children
*/
protected function flattenChildrenArray($children, $parentTitles = [])
{
$output = [];
foreach ($children as $child) {
$childTitles = array_merge($parentTitles, [$child['title']]);
$grandChildren = $child['children'];
$contextString = implode('/', $parentTitles);
$child['contextString'] = ($contextString !== '') ? $contextString .'/' : '';
$child['children'] = [];
if (!$this->search || in_array($child['id'], $this->realSearchIds)) {
$output[] = $child;
}
$output = array_merge($output, $this->flattenChildrenArray($grandChildren, $childTitles));
}
return $output;
}
/**
* Populate $this->searchIds with the IDs of the pages matching the searched parameter and their parents.
* Reverse-constructs the tree starting from the leaves. Initially taken from CMSSiteTreeFilter, but modified
* with pluggable search function.
*/
protected function populateIDs()
{
// get all the leaves to be displayed
$res = $this->getSearchResults();
if (!$res) {
return;
}
// iteratively fetch the parents in bulk, until all the leaves can be accessed using the tree control
foreach ($res as $row) {
if ($row->ParentID) {
$parents[$row->ParentID] = true;
}
$this->searchIds[$row->ID] = true;
}
$this->realSearchIds = $res->column();
$sourceObject = $this->sourceObject;
while (!empty($parents)) {
$items = DataObject::get($sourceObject)
->filter("ID", array_keys($parents));
$parents = array();
foreach ($items as $item) {
if ($item->ParentID) {
$parents[$item->ParentID] = true;
}
$this->searchIds[$item->ID] = true;
$this->searchExpanded[$item->ID] = true;
}
}
}
/**
* Get the DataObjects that matches the searched parameter.
*
* @return DataList
*/
protected function getSearchResults()
{
if ($this->searchCallback) {
return call_user_func($this->searchCallback, $this->sourceObject, $this->labelField, $this->search);
}
$sourceObject = $this->sourceObject;
$filters = array();
if (singleton($sourceObject)->hasDatabaseField($this->labelField)) {
$filters["{$this->labelField}:PartialMatch"] = $this->search;
} else {
if (singleton($sourceObject)->hasDatabaseField('Title')) {
$filters["Title:PartialMatch"] = $this->search;
}
if (singleton($sourceObject)->hasDatabaseField('Name')) {
$filters["Name:PartialMatch"] = $this->search;
}
}
if (empty($filters)) {
throw new InvalidArgumentException(sprintf(
'Cannot query by %s.%s, not a valid database column',
$sourceObject,
$this->labelField
));
}
return DataObject::get($this->sourceObject)->filterAny($filters);
}
/**
* Get the object where the $keyField is equal to a certain value
*
* @param string|int $key
* @return DataObject
*/
protected function objectForKey($key)
{
return DataObject::get($this->sourceObject)
->filter($this->keyField, $key)
->first();
}
/**
* Changes this field to the readonly field.
*/
public function performReadonlyTransformation()
{
/** @var TreeDropdownField_Readonly $copy */
$copy = $this->castedCopy(TreeDropdownField_Readonly::class);
$copy->setKeyField($this->keyField);
$copy->setLabelField($this->labelField);
$copy->setSourceObject($this->sourceObject);
return $copy;
}
/**
* @param string|FormField $classOrCopy
* @return FormField
*/
public function castedCopy($classOrCopy)
{
$field = $classOrCopy;
if (!is_object($field)) {
$field = new $classOrCopy($this->name, $this->title, $this->sourceObject);
}
return parent::castedCopy($field);
}
public function getSchemaStateDefaults()
{
$data = parent::getSchemaStateDefaults();
// Check label for field
$record = $this->Value() ? $this->objectForKey($this->Value()) : null;
$selectedlabel = null;
// Ensure cache is keyed by last modified date of the underlying list
$data['data']['cacheKey'] = DataList::create($this->sourceObject)->max('LastEdited');
if ($record) {
$data['data']['valueObject'] = [
'id' => $record->getField($this->keyField),
'title' => $record->getTitle(),
'treetitle' => $record->obj($this->labelField)->getSchemaValue(),
];
}
return $data;
}
public function getSchemaDataDefaults()
{
$data = parent::getSchemaDataDefaults();
$data['data'] = array_merge($data['data'], [
'urlTree' => $this->Link('tree'),
'showSearch' => $this->showSearch,
'emptyString' => $this->getEmptyString(),
'hasEmptyDefault' => $this->getHasEmptyDefault(),
]);
return $data;
}
/**
* @param boolean $bool
* @return self Self reference
*/
public function setHasEmptyDefault($bool)
{
$this->hasEmptyDefault = $bool;
return $this;
}
/**
* @return bool
*/
public function getHasEmptyDefault()
{
return $this->hasEmptyDefault;
}
/**
* Set the default selection label, e.g. "select...".
* Defaults to an empty string. Automatically sets
* {@link $hasEmptyDefault} to true.
*
* @param string $string
* @return $this
*/
public function setEmptyString($string)
{
$this->setHasEmptyDefault(true);
$this->emptyString = $string;
return $this;
}
/**
* @return string
*/
public function getEmptyString()
{
if ($this->emptyString !== null) {
return $this->emptyString;
}
$item = DataObject::singleton($this->sourceObject);
$emptyString = _t(
'SilverStripe\\Forms\\DropdownField.CHOOSE_MODEL',
'(Choose {name})',
['name' => $item->i18n_singular_name()]
);
return $emptyString;
}
}