Passed
Push — master ( 493c3e...a4042e )
by Thomas
03:08
created

TabulatorGrid::addToolEnd()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace LeKoala\Tabulator;
4
5
use Exception;
6
use RuntimeException;
7
use SilverStripe\i18n\i18n;
8
use SilverStripe\Forms\Form;
9
use InvalidArgumentException;
10
use LeKoala\Tabulator\BulkActions\BulkDeleteAction;
11
use SilverStripe\ORM\SS_List;
12
use SilverStripe\Core\Convert;
13
use SilverStripe\ORM\DataList;
14
use SilverStripe\ORM\ArrayList;
15
use SilverStripe\Core\ClassInfo;
16
use SilverStripe\ORM\DataObject;
17
use SilverStripe\View\ArrayData;
18
use SilverStripe\Forms\FieldList;
19
use SilverStripe\Forms\FormField;
20
use SilverStripe\Control\Director;
21
use SilverStripe\View\Requirements;
22
use SilverStripe\Control\Controller;
23
use SilverStripe\Control\HTTPRequest;
24
use SilverStripe\Control\HTTPResponse;
25
use SilverStripe\ORM\FieldType\DBEnum;
26
use SilverStripe\Control\RequestHandler;
27
use SilverStripe\Core\Injector\Injector;
28
use SilverStripe\Security\SecurityToken;
29
use SilverStripe\ORM\DataObjectInterface;
30
use SilverStripe\ORM\FieldType\DBBoolean;
31
use SilverStripe\Forms\GridField\GridFieldConfig;
32
use SilverStripe\ORM\Filters\PartialMatchFilter;
33
34
/**
35
 * This is a replacement for most GridField usages in SilverStripe
36
 * It can easily work in the frontend too
37
 *
38
 * @link http://www.tabulator.info/
39
 */
40
class TabulatorGrid extends FormField
41
{
42
    const POS_START = 'start';
43
    const POS_END = 'end';
44
45
    const UI_ADD = "ui_add";
46
    const UI_EDIT = "ui_edit";
47
    const UI_DELETE = "ui_delete";
48
    const UI_VIEW = "ui_view";
49
    const UI_SORT = "ui_sort";
50
51
    const TOOL_ADD_NEW = "add_new";
52
    const TOOL_EXPORT = "export";
53
54
    // @link http://www.tabulator.info/examples/5.5?#fittodata
55
    const LAYOUT_FIT_DATA = "fitData";
56
    const LAYOUT_FIT_DATA_FILL = "fitDataFill";
57
    const LAYOUT_FIT_DATA_STRETCH = "fitDataStretch";
58
    const LAYOUT_FIT_DATA_TABLE = "fitDataTable";
59
    const LAYOUT_FIT_COLUMNS = "fitColumns";
60
61
    const RESPONSIVE_LAYOUT_HIDE = "hide";
62
    const RESPONSIVE_LAYOUT_COLLAPSE = "collapse";
63
64
    // @link http://www.tabulator.info/docs/5.5/format
65
    const FORMATTER_PLAINTEXT = 'plaintext';
66
    const FORMATTER_TEXTAREA = 'textarea';
67
    const FORMATTER_HTML = 'html';
68
    const FORMATTER_MONEY = 'money';
69
    const FORMATTER_IMAGE = 'image';
70
    const FORMATTER_LINK = 'link';
71
    const FORMATTER_DATETIME = 'datetime';
72
    const FORMATTER_DATETIME_DIFF = 'datetimediff';
73
    const FORMATTER_TICKCROSS = 'tickCross';
74
    const FORMATTER_COLOR = 'color';
75
    const FORMATTER_STAR = 'star';
76
    const FORMATTER_TRAFFIC = 'traffic';
77
    const FORMATTER_PROGRESS = 'progress';
78
    const FORMATTER_LOOKUP = 'lookup';
79
    const FORMATTER_BUTTON_TICK = 'buttonTick';
80
    const FORMATTER_BUTTON_CROSS = 'buttonCross';
81
    const FORMATTER_ROWNUM = 'rownum';
82
    const FORMATTER_HANDLE = 'handle';
83
    // @link http://www.tabulator.info/docs/5.5/format#format-module
84
    const FORMATTER_ROW_SELECTION = 'rowSelection';
85
    const FORMATTER_RESPONSIVE_COLLAPSE = 'responsiveCollapse';
86
87
    // our built in functions
88
    const JS_BOOL_GROUP_HEADER = 'SSTabulator.boolGroupHeader';
89
    const JS_DATA_AJAX_RESPONSE = 'SSTabulator.dataAjaxResponse';
90
    const JS_INIT_CALLBACK = 'SSTabulator.initCallback';
91
    const JS_CONFIG_CALLBACK = 'SSTabulator.configCallback';
92
93
    /**
94
     * @config
95
     */
96
    private static array $allowed_actions = [
97
        'load',
98
        'handleItem',
99
        'handleTool',
100
        'configProvider',
101
        'autocomplete',
102
        'handleBulkAction',
103
    ];
104
105
    private static $url_handlers = [
106
        'item/$ID' => 'handleItem',
107
        'tool/$ID' => 'handleTool',
108
        'bulkAction/$ID' => 'handleBulkAction',
109
    ];
110
111
    private static array $casting = [
112
        'JsonOptions' => 'HTMLFragment',
113
        'ShowTools' => 'HTMLFragment',
114
        'dataAttributesHTML' => 'HTMLFragment',
115
    ];
116
117
    /**
118
     * @config
119
     */
120
    private static bool $load_styles = true;
121
122
    /**
123
     * @config
124
     */
125
    private static string $luxon_version = '3';
126
127
    /**
128
     * @config
129
     */
130
    private static string $last_icon_version = '2';
131
132
    /**
133
     * @config
134
     */
135
    private static bool $use_cdn = false;
136
137
    /**
138
     * @config
139
     */
140
    private static bool $enable_luxon = false;
141
142
    /**
143
     * @config
144
     */
145
    private static bool $enable_last_icon = false;
146
147
    /**
148
     * @config
149
     */
150
    private static bool $enable_requirements = true;
151
152
    /**
153
     * @config
154
     */
155
    private static bool $enable_js_modules = true;
156
157
    /**
158
     * @link http://www.tabulator.info/docs/5.5/options
159
     * @config
160
     */
161
    private static array $default_options = [
162
        'index' => "ID", // http://tabulator.info/docs/5.5/data#row-index
163
        'layout' => 'fitColumns', // http://www.tabulator.info/docs/5.5/layout#layout
164
        'height' => '100%', // http://www.tabulator.info/docs/5.5/layout#height-fixed
165
        'responsiveLayout' => "hide", // http://www.tabulator.info/docs/5.5/layout#responsive
166
    ];
167
168
    /**
169
     * @link http://tabulator.info/docs/5.5/columns#defaults
170
     * @config
171
     */
172
    private static array $default_column_options = [
173
        'resizable' => false,
174
    ];
175
176
    private static bool $enable_ajax_init = true;
177
178
    /**
179
     * @config
180
     */
181
    private static bool $default_lazy_init = false;
182
183
    /**
184
     * @config
185
     */
186
    private static bool $show_row_delete = false;
187
188
    /**
189
     * Data source.
190
     */
191
    protected ?SS_List $list;
192
193
    /**
194
     * @link http://www.tabulator.info/docs/5.5/columns
195
     */
196
    protected array $columns = [];
197
198
    /**
199
     * @link http://tabulator.info/docs/5.5/columns#defaults
200
     */
201
    protected array $columnDefaults = [];
202
203
    /**
204
     * @link http://www.tabulator.info/docs/5.5/options
205
     */
206
    protected array $options = [];
207
208
    protected bool $autoloadDataList = true;
209
210
    protected bool $rowClickTriggersAction = false;
211
212
    protected int $pageSize = 10;
213
214
    protected string $itemRequestClass = '';
215
216
    protected string $modelClass = '';
217
218
    protected bool $lazyInit = false;
219
220
    protected array $tools = [];
221
222
    /**
223
     * @var AbstractBulkAction[]
224
     */
225
    protected array $bulkActions = [];
226
227
    protected array $listeners = [];
228
229
    protected array $linksOptions = [
230
        'ajaxURL'
231
    ];
232
233
    protected array $dataAttributes = [];
234
235
    protected string $controllerFunction = "";
236
237
    protected string $editUrl = "";
238
239
    protected string $moveUrl = "";
240
241
    protected string $bulkUrl = "";
242
243
    protected bool $globalSearch = false;
244
245
    protected array $wildcardFields = [];
246
247
    protected array $quickFilters = [];
248
249
    protected string $defaultFilter = 'PartialMatch';
250
251
    protected bool $groupLayout = false;
252
253
    protected bool $enableGridManipulation = false;
254
255
    /**
256
     * @param string $fieldName
257
     * @param string|null|bool $title
258
     * @param SS_List $value
259
     */
260
    public function __construct($name, $title = null, $value = null)
261
    {
262
        // Set options and defaults first
263
        $this->options = self::config()->default_options ?? [];
264
        $this->columnDefaults = self::config()->default_column_options ?? [];
265
266
        parent::__construct($name, $title, $value);
267
        $this->setLazyInit(self::config()->default_lazy_init);
268
269
        // We don't want regular setValue for this since it would break with loadFrom logic
270
        if ($value) {
271
            $this->setList($value);
272
        }
273
    }
274
275
    /**
276
     * This helps if some third party code expects the TabulatorGrid to be a GridField
277
     * Only works to a really basic extent
278
     */
279
    public function getConfig(): GridFieldConfig
280
    {
281
        return new GridFieldConfig;
282
    }
283
284
    /**
285
     * This helps if some third party code expects the TabulatorGrid to be a GridField
286
     * Only works to a really basic extent
287
     */
288
    public function setConfig($config)
289
    {
290
        // ignore
291
    }
292
293
    /**
294
     * @return string
295
     */
296
    public function getValueJson()
297
    {
298
        $v = $this->value ?? '';
299
        if (is_array($v)) {
300
            $v = json_encode($v);
301
        }
302
        if (strpos($v, '[') !== 0) {
303
            return '[]';
304
        }
305
        return $v;
306
    }
307
308
    public function saveInto(DataObjectInterface $record)
309
    {
310
        if ($this->enableGridManipulation) {
311
            $value = $this->dataValue();
312
            if (is_array($value)) {
313
                $this->value = json_encode(array_values($value));
314
            }
315
            parent::saveInto($record);
316
        }
317
    }
318
319
    /**
320
     * Temporary link that will be replaced by a real link by processLinks
321
     * TODO: not really happy with this, find a better way
322
     *
323
     * @param string $action
324
     * @return string
325
     */
326
    public function TempLink(string $action, bool $controller = true): string
327
    {
328
        // It's an absolute link
329
        if (strpos($action, '/') === 0 || strpos($action, 'http') === 0) {
330
            return $action;
331
        }
332
        // Already temp
333
        if (strpos($action, ':') !== false) {
334
            return $action;
335
        }
336
        $prefix = $controller ? "controller" : "form";
337
        return "$prefix:$action";
338
    }
339
340
    public function ControllerLink(string $action): string
341
    {
342
        return $this->getForm()->getController()->Link($action);
343
    }
344
345
    public function getCreateLink(): string
346
    {
347
        return Controller::join_links($this->Link('item'), 'new');
348
    }
349
350
    /**
351
     * @param FieldList $fields
352
     * @param string $name
353
     * @return TabulatorGrid|null
354
     */
355
    public static function replaceGridField(FieldList $fields, string $name)
356
    {
357
        /** @var \SilverStripe\Forms\GridField\GridField $gridField */
358
        $gridField = $fields->dataFieldByName($name);
359
        if (!$gridField) {
0 ignored issues
show
introduced by
$gridField is of type SilverStripe\Forms\GridField\GridField, thus it always evaluated to true.
Loading history...
360
            return;
361
        }
362
        if ($gridField instanceof TabulatorGrid) {
0 ignored issues
show
introduced by
$gridField is never a sub-type of LeKoala\Tabulator\TabulatorGrid.
Loading history...
363
            return $gridField;
364
        }
365
        $tabulatorGrid = new TabulatorGrid($name, $gridField->Title(), $gridField->getList());
366
        // In the cms, this is mostly never happening
367
        if ($gridField->getForm()) {
368
            $tabulatorGrid->setForm($gridField->getForm());
369
        }
370
        $tabulatorGrid->configureFromDataObject($gridField->getModelClass());
371
        $tabulatorGrid->setLazyInit(true);
372
        $fields->replaceField($name, $tabulatorGrid);
373
374
        return $tabulatorGrid;
375
    }
376
377
    /**
378
     * A shortcut to convert editable records to view only
379
     * Disables adding new records as well
380
     */
381
    public function setViewOnly(): void
382
    {
383
        $itemUrl = $this->TempLink('item/{ID}', false);
384
        $this->removeButton(self::UI_EDIT);
385
        $this->removeButton(self::UI_DELETE);
386
        $this->addButton(self::UI_VIEW, $itemUrl, "visibility", "View");
387
        $this->removeTool(TabulatorAddNewButton::class);
388
    }
389
390
    public function isViewOnly(): bool
391
    {
392
        return !$this->hasButton(self::UI_EDIT);
393
    }
394
395
    public function configureFromDataObject($className = null): void
396
    {
397
        $this->columns = [];
398
399
        if (!$className) {
400
            $className = $this->getModelClass();
401
        }
402
        if (!$className) {
403
            throw new RuntimeException("Could not find the model class");
404
        }
405
        $this->modelClass = $className;
406
407
        /** @var DataObject $singl */
408
        $singl = singleton($className);
409
410
        $opts = [];
411
        if ($singl->hasMethod('tabulatorOptions')) {
412
            $opts = $singl->tabulatorOptions();
413
        }
414
415
        // Mock some base columns using SilverStripe built-in methods
416
        $columns = [];
417
418
        $summaryFields = $opts['summaryFields'] ?? $singl->summaryFields();
419
        foreach ($summaryFields as $field => $title) {
420
            // Deal with this in load() instead
421
            // if (strpos($field, '.') !== false) {
422
            // $fieldParts = explode(".", $field);
423
424
            // It can be a relation Users.Count or a field Field.Nice
425
            // $classOrField = $fieldParts[0];
426
            // $relationOrMethod = $fieldParts[1];
427
            // }
428
            $title = str_replace(".", " ", $title);
429
            $columns[$field] = [
430
                'field' => $field,
431
                'title' => $title,
432
            ];
433
434
            $dbObject = $singl->dbObject($field);
435
            if ($dbObject) {
436
                if ($dbObject instanceof DBBoolean) {
437
                    $columns[$field]['formatter'] = "customTickCross";
438
                }
439
            }
440
        }
441
        $summaryFields = $opts['searchableFields'] ?? $singl->searchableFields();
0 ignored issues
show
Unused Code introduced by
The assignment to $summaryFields is dead and can be removed.
Loading history...
442
        foreach ($singl->searchableFields() as $key => $searchOptions) {
443
            /*
444
            "filter" => "NameOfTheFilter"
445
            "field" => "SilverStripe\Forms\FormField"
446
            "title" => "Title of the field"
447
            */
448
            if (!isset($columns[$key])) {
449
                continue;
450
            }
451
            $columns[$key]['headerFilter'] = true;
452
            // $columns[$key]['headerFilterPlaceholder'] = $searchOptions['title'];
453
            //TODO: implement filter mapping
454
            switch ($searchOptions['filter']) {
455
                default:
456
                    $columns[$key]['headerFilterFunc'] =  "like";
457
                    break;
458
            }
459
460
            // Restrict based on data type
461
            $dbObject = $singl->dbObject($key);
462
            if ($dbObject) {
463
                if ($dbObject instanceof DBBoolean) {
464
                    $columns[$key]['headerFilter'] = 'tickCross';
465
                    $columns[$key]['headerFilterFunc'] =  "=";
466
                    $columns[$key]['headerFilterParams'] =  [
467
                        'tristate' => true
468
                    ];
469
                }
470
                if ($dbObject instanceof DBEnum) {
471
                    $columns[$key]['headerFilter'] = 'list';
472
                    $columns[$key]['headerFilterFunc'] =  "=";
473
                    $columns[$key]['headerFilterParams'] =  [
474
                        'values' => $dbObject->enumValues()
475
                    ];
476
                }
477
            }
478
        }
479
480
        // Allow customizing our columns based on record
481
        if ($singl->hasMethod('tabulatorColumns')) {
482
            $fields = $singl->tabulatorColumns();
483
            if (!is_array($fields)) {
484
                throw new RuntimeException("tabulatorColumns must return an array");
485
            }
486
            foreach ($fields as $key => $columnOptions) {
487
                $baseOptions = $columns[$key] ?? [];
488
                $columns[$key] = array_merge($baseOptions, $columnOptions);
489
            }
490
        }
491
492
        $this->extend('updateConfiguredColumns', $columns);
493
494
        foreach ($columns as $col) {
495
            $this->addColumn($col['field'], $col['title'], $col);
496
        }
497
498
        // Sortable ?
499
        $sortable = $opts['sortable'] ?? $singl->hasField('Sort');
500
        if ($sortable) {
501
            $this->wizardMoveable();
502
        }
503
504
        // Actions
505
        // We use a pseudo link, because maybe we cannot call Link() yet if it's not linked to a form
506
507
        $this->bulkUrl = $this->TempLink("bulkAction/", false);
508
509
        // - Core actions, handled by TabulatorGrid
510
        $itemUrl = $this->TempLink('item/{ID}', false);
511
        if ($singl->canEdit()) {
512
            $this->addButton(self::UI_EDIT, $itemUrl, "edit", _t('TabulatorGrid.Edit', 'Edit'));
513
            $this->editUrl = $this->TempLink("item/{ID}/ajaxEdit", false);
514
        } elseif ($singl->canView()) {
515
            $this->addButton(self::UI_VIEW, $itemUrl, "visibility", _t('TabulatorGrid.View', 'View'));
516
        }
517
518
        $showRowDelete = $opts['rowDelete'] ?? self::config()->show_row_delete;
519
        if ($singl->canDelete() && $showRowDelete) {
520
            $deleteBtn = $this->makeButton($this->TempLink('item/{ID}/delete', false), "delete", _t('TabulatorGrid.Delete', 'Delete'));
521
            $deleteBtn["formatterParams"]["classes"] = 'btn btn-danger';
522
            $this->addButtonFromArray("ui_delete", $deleteBtn);
523
        }
524
525
        // - Tools
526
        $this->tools = [];
527
528
        $addNew = $opts['addNew'] ?? true;
529
        if ($singl->canCreate() && $addNew) {
530
            $this->addTool(self::POS_START, new TabulatorAddNewButton($this), self::TOOL_ADD_NEW);
0 ignored issues
show
Unused Code introduced by
The call to LeKoala\Tabulator\Tabula...ewButton::__construct() has too many arguments starting with $this. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

530
            $this->addTool(self::POS_START, /** @scrutinizer ignore-call */ new TabulatorAddNewButton($this), self::TOOL_ADD_NEW);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
531
        }
532
        $export = $opts['export'] ?? true;
533
        if (class_exists(\LeKoala\ExcelImportExport\ExcelImportExport::class) && $export) {
0 ignored issues
show
Bug introduced by
The type LeKoala\ExcelImportExport\ExcelImportExport was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
534
            $this->addTool(self::POS_END, new TabulatorExportButton($this), self::TOOL_EXPORT);
0 ignored issues
show
Unused Code introduced by
The call to LeKoala\Tabulator\Tabula...rtButton::__construct() has too many arguments starting with $this. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

534
            $this->addTool(self::POS_END, /** @scrutinizer ignore-call */ new TabulatorExportButton($this), self::TOOL_EXPORT);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
535
        }
536
537
        // - Custom actions are forwarded to the model itself
538
        if ($singl->hasMethod('tabulatorRowActions')) {
539
            $rowActions = $singl->tabulatorRowActions();
540
            if (!is_array($rowActions)) {
541
                throw new RuntimeException("tabulatorRowActions must return an array");
542
            }
543
            foreach ($rowActions as $key => $actionConfig) {
544
                $action = $actionConfig['action'] ?? $key;
545
                $url = $this->TempLink("item/{ID}/customAction/$action", false);
546
                $icon = $actionConfig['icon'] ?? "cog";
547
                $title = $actionConfig['title'] ?? "";
548
549
                $button = $this->makeButton($url, $icon, $title);
550
                if (!empty($actionConfig['ajax'])) {
551
                    $button['formatterParams']['ajax'] = true;
552
                }
553
                $this->addButtonFromArray("ui_customaction_$action", $button);
554
            }
555
        }
556
557
        $this->setRowClickTriggersAction(true);
558
    }
559
560
    public static function requirements(): void
561
    {
562
        $load_styles = self::config()->load_styles;
563
        $luxon_version = self::config()->luxon_version;
564
        $enable_luxon = self::config()->enable_luxon;
565
        $last_icon_version = self::config()->last_icon_version;
566
        $enable_last_icon = self::config()->enable_last_icon;
567
        $enable_js_modules = self::config()->enable_js_modules;
568
569
        $jsOpts = [];
570
        if ($enable_js_modules) {
571
            $jsOpts['type'] = 'module';
572
        }
573
574
        if ($luxon_version && $enable_luxon) {
575
            // Do not load as module or we would get undefined luxon global var
576
            Requirements::javascript("https://cdn.jsdelivr.net/npm/luxon@$luxon_version/build/global/luxon.min.js");
577
        }
578
        if ($last_icon_version && $enable_last_icon) {
579
            Requirements::css("https://cdn.jsdelivr.net/npm/last-icon@$last_icon_version/last-icon.min.css");
580
            // Do not load as module even if asked to ensure load speed
581
            Requirements::javascript("https://cdn.jsdelivr.net/npm/last-icon@$last_icon_version/last-icon.min.js");
582
        }
583
584
        Requirements::javascript('lekoala/silverstripe-tabulator:client/TabulatorField.js', $jsOpts);
585
        if ($load_styles) {
586
            Requirements::css('lekoala/silverstripe-tabulator:client/custom-tabulator.css');
587
            Requirements::javascript('lekoala/silverstripe-tabulator:client/tabulator-grid.min.js', $jsOpts);
588
        } else {
589
            // you must load th css yourself based on your preferences
590
            Requirements::javascript('lekoala/silverstripe-tabulator:client/tabulator-grid.raw.min.js', $jsOpts);
591
        }
592
    }
593
594
    public function setValue($value, $data = null)
595
    {
596
        // Allow set raw json as value
597
        if ($value && is_string($value) && strpos($value, '[') === 0) {
598
            $value = json_decode($value);
599
        }
600
        if ($value instanceof DataList) {
601
            $this->configureFromDataObject($value->dataClass());
602
        }
603
        return parent::setValue($value, $data);
604
    }
605
606
    public function Field($properties = [])
607
    {
608
        if (self::config()->enable_requirements) {
609
            self::requirements();
610
        }
611
612
        // Make sure we can use a standalone version of the field without a form
613
        // Function should match the name
614
        if (!$this->form) {
615
            $this->form = new Form(Controller::curr(), $this->getControllerFunction());
616
        }
617
618
        // Data attributes for our custom behaviour
619
        $this->setDataAttribute("row-click-triggers-action", $this->rowClickTriggersAction);
620
621
        $this->setDataAttribute("listeners", $this->listeners);
622
        if ($this->editUrl) {
623
            $url = $this->processLink($this->editUrl);
624
            $this->setDataAttribute("edit-url", $url);
625
        }
626
        if ($this->moveUrl) {
627
            $url = $this->processLink($this->moveUrl);
628
            $this->setDataAttribute("move-url", $url);
629
        }
630
        if (!empty($this->bulkActions)) {
631
            $url = $this->processLink($this->bulkUrl);
632
            $this->setDataAttribute("bulk-url", $url);
633
        }
634
635
        return parent::Field($properties);
636
    }
637
638
    public function ShowTools(): string
639
    {
640
        if (empty($this->tools)) {
641
            return '';
642
        }
643
        $html = '';
644
        $html .= '<div class="tabulator-tools">';
645
        $html .= '<div class="tabulator-tools-start">';
646
        foreach ($this->tools as $tool) {
647
            if ($tool['position'] != self::POS_START) {
648
                continue;
649
            }
650
            $html .= ($tool['tool'])->forTemplate();
651
        }
652
        $html .= '</div>';
653
        $html .= '<div class="tabulator-tools-end">';
654
        foreach ($this->tools as $tool) {
655
            if ($tool['position'] != self::POS_END) {
656
                continue;
657
            }
658
            $html .= ($tool['tool'])->forTemplate();
659
        }
660
        // Show bulk actions at the end
661
        if (!empty($this->bulkActions)) {
662
            $selectLabel = _t(__CLASS__ . ".BULKSELECT", "Select a bulk action");
663
            $confirmLabel = _t(__CLASS__ . ".BULKCONFIRM", "Go");
664
            $html .= "<select class=\"tabulator-bulk-select\">";
665
            $html .= "<option>" . $selectLabel . "</option>";
666
            foreach ($this->bulkActions as $bulkAction) {
667
                $v = $bulkAction->getName();
668
                $xhr = $bulkAction->getXhr();
669
                $destructive = $bulkAction->getDestructive();
670
                $html .= "<option value=\"$v\" data-xhr=\"$xhr\" data-destructive=\"$destructive\">" . $bulkAction->getLabel() . "</option>";
671
            }
672
            $html .= "</select>";
673
            $html .= "<button class=\"tabulator-bulk-confirm btn\">" . $confirmLabel . "</button>";
674
        }
675
        $html .= '</div>';
676
        $html .= '</div>';
677
        return $html;
678
    }
679
680
    public function JsonOptions(): string
681
    {
682
        $this->processLinks();
683
684
        $data = $this->list ?? [];
685
        if ($this->autoloadDataList && $data instanceof DataList) {
686
            $data = null;
687
        }
688
        $opts = $this->options;
689
        $opts['columnDefaults'] = $this->columnDefaults;
690
691
        if (empty($this->columns)) {
692
            $opts['autoColumns'] = true;
693
        } else {
694
            $opts['columns'] = array_values($this->columns);
695
        }
696
697
        if ($data && is_iterable($data)) {
698
            if ($data instanceof ArrayList) {
699
                $data = $data->toArray();
700
            } else {
701
                if (is_iterable($data) && !is_array($data)) {
702
                    $data = iterator_to_array($data);
703
                }
704
            }
705
            $opts['data'] = $data;
706
        }
707
708
        // i18n
709
        $locale = strtolower(str_replace('_', '-', i18n::get_locale()));
710
        $paginationTranslations = [
711
            "first" => _t("TabulatorPagination.first", "First"),
712
            "first_title" =>  _t("TabulatorPagination.first_title", "First Page"),
713
            "last" =>  _t("TabulatorPagination.last", "Last"),
714
            "last_title" => _t("TabulatorPagination.last_title", "Last Page"),
715
            "prev" => _t("TabulatorPagination.prev", "Previous"),
716
            "prev_title" =>  _t("TabulatorPagination.prev_title", "Previous Page"),
717
            "next" => _t("TabulatorPagination.next", "Next"),
718
            "next_title" =>  _t("TabulatorPagination.next_title", "Next Page"),
719
            "all" =>  _t("TabulatorPagination.all", "All"),
720
        ];
721
        $dataTranslations = [
722
            "loading" => _t("TabulatorData.loading", "Loading"),
723
            "error" => _t("TabulatorData.error", "Error"),
724
        ];
725
        $groupsTranslations = [
726
            "item" => _t("TabulatorGroups.item", "Item"),
727
            "items" => _t("TabulatorGroups.items", "Items"),
728
        ];
729
        $headerFiltersTranslations = [
730
            "default" => _t("TabulatorHeaderFilters.default", "filter column..."),
731
        ];
732
        $bulkActionsTranslations = [
733
            "no_action" => _t("TabulatorBulkActions.no_action", "Please select an action"),
734
            "no_records" => _t("TabulatorBulkActions.no_records", "Please select a record"),
735
            "destructive" => _t("TabulatorBulkActions.destructive", "Confirm destructive action ?"),
736
        ];
737
        $translations = [
738
            'data' => $dataTranslations,
739
            'groups' => $groupsTranslations,
740
            'pagination' => $paginationTranslations,
741
            'headerFilters' => $headerFiltersTranslations,
742
            'bulkActions' => $bulkActionsTranslations,
743
        ];
744
        $opts['locale'] = $locale;
745
        $opts['langs'] = [
746
            $locale => $translations
747
        ];
748
749
        // Apply state
750
        // TODO: finalize persistence on the client side instead of this when using TabID
751
        $state = $this->getState();
752
        if ($state) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $state of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
753
            if (!empty($state['filter'])) {
754
                // @link https://tabulator.info/docs/5.5/filter#initial
755
                // We need to split between global filters and header filters
756
                $allFilters = $state['filter'] ?? [];
757
                $globalFilters = [];
758
                $headerFilters = [];
759
                foreach ($allFilters as $allFilter) {
760
                    if (strpos($allFilter['field'], '__') === 0) {
761
                        $globalFilters[] = $allFilter;
762
                    } else {
763
                        $headerFilters[] = $allFilter;
764
                    }
765
                }
766
                $opts['initialFilter'] = $globalFilters;
767
                $opts['initialHeaderFilter'] = $headerFilters;
768
            }
769
            if (!empty($state['sort'])) {
770
                // @link https://tabulator.info/docs/5.5/sort#initial
771
                $opts['initialSort'] = $state['sort'];
772
            }
773
774
            // Restore state from server
775
            $opts['_state'] = $state;
776
        }
777
778
        if ($this->enableGridManipulation) {
779
            // $opts['renderVertical'] = 'basic';
780
        }
781
782
        // Add our extension initCallback
783
        $opts['_initCallback'] = ['__fn' => self::JS_INIT_CALLBACK];
784
        $opts['_configCallback'] = ['__fn' => self::JS_CONFIG_CALLBACK];
785
786
        unset($opts['height']);
787
        $json = json_encode($opts);
788
789
        // Escape '
790
        $json = str_replace("'", '&#39;', $json);
791
792
        return $json;
793
    }
794
795
    /**
796
     * @param Controller $controller
797
     * @return CompatLayerInterface
798
     */
799
    public function getCompatLayer(Controller $controller = null)
800
    {
801
        if ($controller === null) {
802
            $controller = Controller::curr();
803
        }
804
        if (is_subclass_of($controller, \SilverStripe\Admin\LeftAndMain::class)) {
0 ignored issues
show
Bug introduced by
The type SilverStripe\Admin\LeftAndMain was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
805
            return new SilverstripeAdminCompat();
806
        }
807
        if (is_subclass_of($controller, \LeKoala\Admini\LeftAndMain::class)) {
0 ignored issues
show
Bug introduced by
The type LeKoala\Admini\LeftAndMain was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
808
            return new AdminiCompat();
809
        }
810
    }
811
812
    public function getAttributes()
813
    {
814
        $attrs = parent::getAttributes();
815
        unset($attrs['type']);
816
        unset($attrs['name']);
817
        unset($attrs['value']);
818
        return $attrs;
819
    }
820
821
    public function getOption(string $k)
822
    {
823
        return $this->options[$k] ?? null;
824
    }
825
826
    public function setOption(string $k, $v): self
827
    {
828
        $this->options[$k] = $v;
829
        return $this;
830
    }
831
832
    public function getRowHeight(): int
833
    {
834
        return $this->getOption('rowHeight');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getOption('rowHeight') could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
835
    }
836
837
    /**
838
     * Prevent row height automatic computation
839
     * @link https://tabulator.info/docs/5.5/layout#height-row
840
     */
841
    public function setRowHeight(int $v): self
842
    {
843
        $this->setOption('rowHeight', $v);
844
        return $this;
845
    }
846
847
    public function makeHeadersSticky(): self
848
    {
849
        // note: we could also use the "sticky" attribute on the custom element
850
        $this->addExtraClass("tabulator-sticky");
851
        return $this;
852
    }
853
854
    public function setRemoteSource(string $url, array $extraParams = [], bool $dataResponse = false): self
855
    {
856
        $this->setOption("ajaxURL", $url); //set url for ajax request
857
        $params = array_merge([
858
            'SecurityID' => SecurityToken::getSecurityID()
859
        ], $extraParams);
860
        $this->setOption("ajaxParams", $params);
861
        // Accept response where data is nested under the data key
862
        if ($dataResponse) {
863
            $this->setOption("ajaxResponse", ['__fn' => self::JS_DATA_AJAX_RESPONSE]);
864
        }
865
        return $this;
866
    }
867
868
    /**
869
     * @link http://www.tabulator.info/docs/5.5/page#remote
870
     * @param string $url
871
     * @param array $params
872
     * @param integer $pageSize
873
     * @param integer $initialPage
874
     */
875
    public function setRemotePagination(string $url, array $params = [], int $pageSize = 0, int $initialPage = 1): self
876
    {
877
        $this->setOption("pagination", true); //enable pagination
878
        $this->setOption("paginationMode", 'remote'); //enable remote pagination
879
        $this->setRemoteSource($url, $params);
880
        if (!$pageSize) {
881
            $pageSize = $this->pageSize;
882
        } else {
883
            $this->pageSize = $pageSize;
884
        }
885
        $this->setOption("paginationSize", $pageSize);
886
        $this->setOption("paginationInitialPage", $initialPage);
887
        $this->setOption("paginationCounter", 'rows'); // http://www.tabulator.info/docs/5.5/page#counter
888
        return $this;
889
    }
890
891
    public function wizardRemotePagination(int $pageSize = 0, int $initialPage = 1, array $params = []): self
892
    {
893
        $this->setRemotePagination($this->TempLink('load', false), $params, $pageSize, $initialPage);
894
        $this->setOption("sortMode", "remote"); // http://www.tabulator.info/docs/5.5/sort#ajax-sort
895
        $this->setOption("filterMode", "remote"); // http://www.tabulator.info/docs/5.5/filter#ajax-filter
896
        return $this;
897
    }
898
899
    public function setProgressiveLoad(string $url, array $params = [], int $pageSize = 0, int $initialPage = 1, string $mode = 'scroll', int $scrollMargin = 0): self
900
    {
901
        $this->setOption("ajaxURL", $url);
902
        if (!empty($params)) {
903
            $this->setOption("ajaxParams", $params);
904
        }
905
        $this->setOption("progressiveLoad", $mode);
906
        if ($scrollMargin > 0) {
907
            $this->setOption("progressiveLoadScrollMargin", $scrollMargin);
908
        }
909
        if (!$pageSize) {
910
            $pageSize = $this->pageSize;
911
        } else {
912
            $this->pageSize = $pageSize;
913
        }
914
        $this->setOption("paginationSize", $pageSize);
915
        $this->setOption("paginationInitialPage", $initialPage);
916
        $this->setOption("paginationCounter", 'rows'); // http://www.tabulator.info/docs/5.5/page#counter
917
        return $this;
918
    }
919
920
    public function wizardProgressiveLoad(int $pageSize = 0, int $initialPage = 1, string $mode = 'scroll', int $scrollMargin = 0, array $extraParams = []): self
921
    {
922
        $params = array_merge([
923
            'SecurityID' => SecurityToken::getSecurityID()
924
        ], $extraParams);
925
        $this->setProgressiveLoad($this->TempLink('load', false), $params, $pageSize, $initialPage, $mode, $scrollMargin);
926
        $this->setOption("sortMode", "remote"); // http://www.tabulator.info/docs/5.5/sort#ajax-sort
927
        $this->setOption("filterMode", "remote"); // http://www.tabulator.info/docs/5.5/filter#ajax-filter
928
        return $this;
929
    }
930
931
    /**
932
     * @link https://tabulator.info/docs/5.5/layout#responsive
933
     * @param boolean $startOpen
934
     * @param string $mode collapse|hide|flexCollapse
935
     * @return self
936
     */
937
    public function wizardResponsiveCollapse(bool $startOpen = false, string $mode = "collapse"): self
938
    {
939
        $this->setOption("responsiveLayout", $mode);
940
        $this->setOption("responsiveLayoutCollapseStartOpen", $startOpen);
941
        if ($mode != "hide") {
942
            $this->columns = array_merge([
943
                'ui_responsive_collapse' => [
944
                    "cssClass" => 'tabulator-cell-btn',
945
                    'formatter' => 'responsiveCollapse',
946
                    'headerSort' => false,
947
                    'width' => 40,
948
                ]
949
            ], $this->columns);
950
        }
951
        return $this;
952
    }
953
954
    public function wizardDataTree(bool $startExpanded = false, bool $filter = false, bool $sort = false, string $el = null): self
955
    {
956
        $this->setOption("dataTree", true);
957
        $this->setOption("dataTreeStartExpanded", $startExpanded);
958
        $this->setOption("dataTreeFilter", $filter);
959
        $this->setOption("dataTreeSort", $sort);
960
        if ($el) {
961
            $this->setOption("dataTreeElementColumn", $el);
962
        }
963
        return $this;
964
    }
965
966
    /**
967
     * @param array $actions An array of bulk actions, that can extend the abstract one or use the generic with callbable
968
     * @return self
969
     */
970
    public function wizardSelectable(array $actions = []): self
971
    {
972
        $this->columns = array_merge([
973
            'ui_selectable' => [
974
                "hozAlign" => 'center',
975
                "cssClass" => 'tabulator-cell-btn tabulator-cell-selector',
976
                'formatter' => 'rowSelection',
977
                'titleFormatter' => 'rowSelection',
978
                'width' => 40,
979
                'maxWidth' => 40,
980
                "headerSort" => false,
981
            ]
982
        ], $this->columns);
983
        $this->setBulkActions($actions);
984
        return $this;
985
    }
986
987
    public function wizardMoveable(string $callback = "SSTabulator.rowMoved", $field = "Sort"): self
988
    {
989
        $this->moveUrl = $this->TempLink("item/{ID}/ajaxMove", false);
990
        $this->setOption("movableRows", true);
991
        $this->addListener("rowMoved", $callback);
992
        $this->columns = array_merge([
993
            'ui_move' => [
994
                "hozAlign" => 'center',
995
                "cssClass" => 'tabulator-cell-btn tabulator-cell-selector tabulator-ui-sort',
996
                'rowHandle' => true,
997
                'formatter' => 'handle',
998
                'headerSort' => false,
999
                'frozen' => true,
1000
                'width' => 40,
1001
                'maxWidth' => 40,
1002
            ],
1003
            // We need a hidden sort column
1004
            self::UI_SORT => [
1005
                "field" => $field,
1006
                'visible' => false,
1007
            ],
1008
        ], $this->columns);
1009
        return $this;
1010
    }
1011
1012
    /**
1013
     * @param string $field
1014
     * @param string $toggleElement arrow|header|false (header by default)
1015
     * @param boolean $isBool
1016
     * @return void
1017
     */
1018
    public function wizardGroupBy(string $field, string $toggleElement = 'header', bool $isBool = false)
1019
    {
1020
        $this->setOption("groupBy", $field);
1021
        $this->setOption("groupToggleElement", $toggleElement);
1022
        if ($isBool) {
1023
            $this->setOption("groupHeader", ['_fn' => self::JS_BOOL_GROUP_HEADER]);
1024
        }
1025
    }
1026
1027
    /**
1028
     * @param HTTPRequest $request
1029
     * @return HTTPResponse
1030
     */
1031
    public function handleItem($request)
1032
    {
1033
        // Our getController could either give us a true Controller, if this is the top-level GridField.
1034
        // It could also give us a RequestHandler in the form of (GridFieldDetailForm_ItemRequest, TabulatorGrid...)
1035
        $requestHandler = $this->getForm()->getController();
1036
        $record = $this->getRecordFromRequest($request);
1037
        if (!$record) {
1038
            return $requestHandler->httpError(404, 'That record was not found');
1039
        }
1040
        $handler = $this->getItemRequestHandler($record, $requestHandler);
1041
        return $handler->handleRequest($request);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $handler->handleRequest($request) also could return the type SilverStripe\Control\RequestHandler|array|string which is incompatible with the documented return type SilverStripe\Control\HTTPResponse.
Loading history...
1042
    }
1043
1044
    /**
1045
     * @param HTTPRequest $request
1046
     * @return HTTPResponse
1047
     */
1048
    public function handleTool($request)
1049
    {
1050
        // Our getController could either give us a true Controller, if this is the top-level GridField.
1051
        // It could also give us a RequestHandler in the form of (GridFieldDetailForm_ItemRequest, TabulatorGrid...)
1052
        $requestHandler = $this->getForm()->getController();
1053
        $tool = $this->getToolFromRequest($request);
1054
        if (!$tool) {
1055
            return $requestHandler->httpError(404, 'That tool was not found');
1056
        }
1057
        return $tool->handleRequest($request);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $tool->handleRequest($request) also could return the type SilverStripe\Control\RequestHandler|array|string which is incompatible with the documented return type SilverStripe\Control\HTTPResponse.
Loading history...
1058
    }
1059
1060
    /**
1061
     * @param HTTPRequest $request
1062
     * @return HTTPResponse
1063
     */
1064
    public function handleBulkAction($request)
1065
    {
1066
        // Our getController could either give us a true Controller, if this is the top-level GridField.
1067
        // It could also give us a RequestHandler in the form of (GridFieldDetailForm_ItemRequest, TabulatorGrid...)
1068
        $requestHandler = $this->getForm()->getController();
1069
        $bulkAction = $this->getBulkActionFromRequest($request);
1070
        if (!$bulkAction) {
1071
            return $requestHandler->httpError(404, 'That bulk action was not found');
1072
        }
1073
        return $bulkAction->handleRequest($request);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $bulkAction->handleRequest($request) also could return the type SilverStripe\Control\RequestHandler|array|string which is incompatible with the documented return type SilverStripe\Control\HTTPResponse.
Loading history...
1074
    }
1075
1076
    /**
1077
     * @return string name of {@see TabulatorGrid_ItemRequest} subclass
1078
     */
1079
    public function getItemRequestClass(): string
1080
    {
1081
        if ($this->itemRequestClass) {
1082
            return $this->itemRequestClass;
1083
        } elseif (ClassInfo::exists(static::class . '_ItemRequest')) {
1084
            return static::class . '_ItemRequest';
1085
        }
1086
        return TabulatorGrid_ItemRequest::class;
1087
    }
1088
1089
    /**
1090
     * Build a request handler for the given record
1091
     *
1092
     * @param DataObject $record
1093
     * @param RequestHandler $requestHandler
1094
     * @return TabulatorGrid_ItemRequest
1095
     */
1096
    protected function getItemRequestHandler($record, $requestHandler)
1097
    {
1098
        $class = $this->getItemRequestClass();
1099
        $assignedClass = $this->itemRequestClass;
1100
        $this->extend('updateItemRequestClass', $class, $record, $requestHandler, $assignedClass);
1101
        /** @var TabulatorGrid_ItemRequest $handler */
1102
        $handler = Injector::inst()->createWithArgs(
1103
            $class,
1104
            [$this, $record, $requestHandler]
1105
        );
1106
        if ($template = $this->getTemplate()) {
1107
            $handler->setTemplate($template);
1108
        }
1109
        $this->extend('updateItemRequestHandler', $handler);
1110
        return $handler;
1111
    }
1112
1113
    public function getStateKey(string $TabID = null)
1114
    {
1115
        $nested = [];
1116
        $form = $this->getForm();
1117
        $scope = $this->modelClass ? str_replace('_', '\\', $this->modelClass) :  "default";
1118
        if ($form) {
0 ignored issues
show
introduced by
$form is of type SilverStripe\Forms\Form, thus it always evaluated to true.
Loading history...
1119
            $controller = $form->getController();
1120
1121
            // We are in a nested form, track by id since each records needs it own state
1122
            while ($controller instanceof TabulatorGrid_ItemRequest) {
1123
                $record = $controller->getRecord();
1124
                $nested[str_replace('_', '\\', get_class($record))] = $record->ID;
1125
1126
                // Move to parent controller
1127
                $controller = $controller->getController();
1128
            }
1129
1130
            // Scope by top controller class
1131
            $scope = str_replace('_', '\\', get_class($controller));
1132
        }
1133
1134
        $baseKey = 'TabulatorState';
1135
        if ($TabID) {
1136
            $baseKey .= '_' . $TabID;
1137
        }
1138
        $name = $this->getName();
1139
        $key = "$baseKey.$scope.$name";
1140
        foreach ($nested as $k => $v) {
1141
            $key .= "$k.$v";
1142
        }
1143
        return $key;
1144
    }
1145
1146
    /**
1147
     * @param HTTPRequest|null $request
1148
     * @return array{'page': int, 'limit': int, 'sort': array, 'filter': array}
1149
     */
1150
    public function getState(HTTPRequest $request = null)
1151
    {
1152
        if ($request === null) {
1153
            $request = Controller::curr()->getRequest();
1154
        }
1155
        $TabID = $request->requestVar('TabID') ?? null;
1156
        $stateKey = $this->getStateKey($TabID);
1157
        $state = $request->getSession()->get($stateKey);
1158
        return $state ?? [
1159
            'page' => 1,
1160
            'limit' => $this->pageSize,
1161
            'sort' => [],
1162
            'filter' => [],
1163
        ];
1164
    }
1165
1166
    public function setState(HTTPRequest $request, $state)
1167
    {
1168
        $TabID = $request->requestVar('TabID') ?? null;
1169
        $stateKey = $this->getStateKey($TabID);
1170
        $request->getSession()->set($stateKey, $state);
1171
        // If we are in a new controller, we can clear other states
1172
        // Note: this would break tabbed navigation if you try to open multiple tabs, see below for more info
1173
        // @link https://github.com/silverstripe/silverstripe-framework/issues/9556
1174
        $matches = [];
1175
        preg_match_all('/\.(.*?)\./', $stateKey, $matches);
1176
        $scope = $matches[1][0] ?? null;
1177
        if ($scope) {
1178
            self::clearAllStates($scope);
1179
        }
1180
    }
1181
1182
    public function clearState(HTTPRequest $request)
1183
    {
1184
        $TabID = $request->requestVar('TabID') ?? null;
1185
        $stateKey = $this->getStateKey($TabID);
1186
        $request->getSession()->clear($stateKey);
1187
    }
1188
1189
    public static function clearAllStates(string $exceptScope = null, string $TabID = null)
1190
    {
1191
        $request = Controller::curr()->getRequest();
1192
        $baseKey = 'TabulatorState';
1193
        if ($TabID) {
1194
            $baseKey .= '_' . $TabID;
1195
        }
1196
        $allStates = $request->getSession()->get($baseKey);
1197
        if (!$allStates) {
1198
            return;
1199
        }
1200
        foreach ($allStates as $scope => $data) {
1201
            if ($exceptScope && $scope == $exceptScope) {
1202
                continue;
1203
            }
1204
            $request->getSession()->clear("TabulatorState.$scope");
1205
        }
1206
    }
1207
1208
    public function StateValue($key, $field): ?string
1209
    {
1210
        $state = $this->getState();
1211
        $arr = $state[$key] ?? [];
1212
        foreach ($arr as $s) {
1213
            if ($s['field'] === $field) {
1214
                return $s['value'];
1215
            }
1216
        }
1217
        return null;
1218
    }
1219
1220
    /**
1221
     * Provides autocomplete lists
1222
     *
1223
     * @param HTTPRequest $request
1224
     * @return HTTPResponse
1225
     */
1226
    public function autocomplete(HTTPRequest $request)
1227
    {
1228
        if ($this->isDisabled() || $this->isReadonly()) {
1229
            return $this->httpError(403);
1230
        }
1231
        $SecurityID = $request->getVar('SecurityID');
1232
        if (!SecurityToken::inst()->check($SecurityID)) {
1233
            return $this->httpError(404, "Invalid SecurityID");
1234
        }
1235
1236
        $name = $request->getVar("Column");
1237
        $col = $this->getColumn($name);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type null; however, parameter $key of LeKoala\Tabulator\TabulatorGrid::getColumn() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1237
        $col = $this->getColumn(/** @scrutinizer ignore-type */ $name);
Loading history...
1238
        if (!$col) {
1239
            return $this->httpError(403, "Invalid column");
1240
        }
1241
1242
        // Don't use % term as it prevents use of indexes
1243
        $term = $request->getVar('term') . '%';
1244
        $term = str_replace(' ', '%', $term);
1245
1246
        $parts = explode(".", $name);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1246
        $parts = explode(".", /** @scrutinizer ignore-type */ $name);
Loading history...
1247
        if (count($parts) > 2) {
1248
            array_pop($parts);
1249
        }
1250
        if (count($parts) == 2) {
1251
            $class = $parts[0];
1252
            $field = $parts[1];
1253
        } elseif (count($parts) == 1) {
1254
            $class = preg_replace("/ID$/", "", $parts[0]);
1255
            $field = 'Title';
1256
        } else {
1257
            return $this->httpError(403, "Invalid field");
1258
        }
1259
1260
        /** @var DataObject $sng */
1261
        $sng = $class::singleton();
1262
        $baseTable = $sng->baseTable();
1263
1264
        $searchField = null;
1265
        $searchCandidates = [
1266
            $field, 'Name', 'Surname', 'Email', 'ID'
1267
        ];
1268
1269
        // Ensure field exists, this is really rudimentary
1270
        $db = $class::config()->db;
1271
        foreach ($searchCandidates as $searchCandidate) {
1272
            if ($searchField) {
1273
                continue;
1274
            }
1275
            if (isset($db[$searchCandidate])) {
1276
                $searchField = $searchCandidate;
1277
            }
1278
        }
1279
        $searchCols = [$searchField];
1280
1281
        // For members, do something better
1282
        if ($baseTable == 'Member') {
1283
            $searchField = ['FirstName', 'Surname'];
1284
            $searchCols = ['FirstName', 'Surname', 'Email'];
1285
        }
1286
1287
        if (!empty($col['editorParams']['customSearchField'])) {
1288
            $searchField = $col['editorParams']['customSearchField'];
1289
        }
1290
        if (!empty($col['editorParams']['customSearchCols'])) {
1291
            $searchCols = $col['editorParams']['customSearchCols'];
1292
        }
1293
1294
        // Note: we need to use the orm, even if it's slower, to make sure any extension is properly applied
1295
        /** @var DataList $list */
1296
        $list = $sng::get();
1297
1298
        // Make sure at least one field is not null...
1299
        $where = [];
1300
        foreach ($searchCols as $searchCol) {
1301
            $where[] = $searchCol . ' IS NOT NULL';
1302
        }
1303
        $list = $list->where($where);
1304
        // ... and matches search term ...
1305
        $where = [];
1306
        foreach ($searchCols as $searchCol) {
1307
            $where[$searchCol . ' LIKE ?'] = $term;
1308
        }
1309
        $list = $list->whereAny($where);
1310
1311
        // ... and any user set requirements
1312
        if (!empty($col['editorParams']['where'])) {
1313
            // Deal with in clause
1314
            $customWhere = [];
1315
            foreach ($col['editorParams']['where'] as $col => $param) {
1316
                // For array, we need a IN statement with a ? for each value
1317
                if (is_array($param)) {
1318
                    $prepValue = [];
1319
                    $params = [];
1320
                    foreach ($param as $paramValue) {
1321
                        $params[] = $paramValue;
1322
                        $prepValue[] = "?";
1323
                    }
1324
                    $customWhere["$col IN (" . implode(',', $prepValue) . ")"] = $params;
1325
                } else {
1326
                    $customWhere["$col = ?"] = $param;
1327
                }
1328
            }
1329
            $list = $list->where($customWhere);
1330
        }
1331
1332
        $results = iterator_to_array($list);
1333
        $data = [];
1334
        foreach ($results as $record) {
1335
            if (is_array($searchField)) {
1336
                $labelParts = [];
1337
                foreach ($searchField as $sf) {
1338
                    $labelParts[] = $record->$sf;
1339
                }
1340
                $label = implode(" ", $labelParts);
1341
            } else {
1342
                $label = $record->$searchField;
1343
            }
1344
            $data[] = [
1345
                'value' => $record->ID,
1346
                'label' => $label,
1347
            ];
1348
        }
1349
1350
        $json = json_encode($data);
1351
        $response = new HTTPResponse($json);
1352
        $response->addHeader('Content-Type', 'application/script');
1353
        return $response;
1354
    }
1355
1356
    /**
1357
     * @link http://www.tabulator.info/docs/5.5/page#remote-response
1358
     * @param HTTPRequest $request
1359
     * @return HTTPResponse
1360
     */
1361
    public function load(HTTPRequest $request)
1362
    {
1363
        if ($this->isDisabled() || $this->isReadonly()) {
1364
            return $this->httpError(403);
1365
        }
1366
        $SecurityID = $request->getVar('SecurityID');
1367
        if (!SecurityToken::inst()->check($SecurityID)) {
1368
            return $this->httpError(404, "Invalid SecurityID");
1369
        }
1370
1371
        $page = (int) $request->getVar('page');
1372
        $limit = (int) $request->getVar('size');
1373
1374
        $sort = $request->getVar('sort');
1375
        $filter = $request->getVar('filter');
1376
1377
        // Persist state to allow the ItemEditForm to display navigation
1378
        $state = [
1379
            'page' => $page,
1380
            'limit' => $limit,
1381
            'sort' => $sort,
1382
            'filter' => $filter,
1383
        ];
1384
        $this->setState($request, $state);
1385
1386
        $offset = ($page - 1) * $limit;
1387
        $data = $this->getManipulatedData($limit, $offset, $sort, $filter);
1388
        $data['state'] = $state;
1389
1390
        $encodedData = json_encode($data);
1391
        if (!$encodedData) {
1392
            throw new Exception(json_last_error_msg());
1393
        }
1394
1395
        $response = new HTTPResponse($encodedData);
1396
        $response->addHeader('Content-Type', 'application/json');
1397
        return $response;
1398
    }
1399
1400
    /**
1401
     * @param HTTPRequest $request
1402
     * @return DataObject|null
1403
     */
1404
    protected function getRecordFromRequest(HTTPRequest $request): ?DataObject
1405
    {
1406
        /** @var DataObject $record */
1407
        if (is_numeric($request->param('ID'))) {
1408
            /** @var Filterable $dataList */
1409
            $dataList = $this->getList();
1410
            $record = $dataList->byID($request->param('ID'));
1411
        } else {
1412
            $record = Injector::inst()->create($this->getModelClass());
1413
        }
1414
        return $record;
1415
    }
1416
1417
    /**
1418
     * @param HTTPRequest $request
1419
     * @return AbstractTabulatorTool|null
1420
     */
1421
    protected function getToolFromRequest(HTTPRequest $request): ?AbstractTabulatorTool
1422
    {
1423
        $toolID = $request->param('ID');
1424
        $tool = $this->getTool($toolID);
1425
        return $tool;
1426
    }
1427
1428
    /**
1429
     * @param HTTPRequest $request
1430
     * @return AbstractBulkAction|null
1431
     */
1432
    protected function getBulkActionFromRequest(HTTPRequest $request): ?AbstractBulkAction
1433
    {
1434
        $toolID = $request->param('ID');
1435
        $tool = $this->getBulkAction($toolID);
1436
        return $tool;
1437
    }
1438
1439
    /**
1440
     * Get the value of a named field  on the given record.
1441
     *
1442
     * Use of this method ensures that any special rules around the data for this gridfield are
1443
     * followed.
1444
     *
1445
     * @param DataObject $record
1446
     * @param string $fieldName
1447
     *
1448
     * @return mixed
1449
     */
1450
    public function getDataFieldValue($record, $fieldName)
1451
    {
1452
        if ($record->hasMethod('relField')) {
1453
            return $record->relField($fieldName);
1454
        }
1455
1456
        if ($record->hasMethod($fieldName)) {
1457
            return $record->$fieldName();
1458
        }
1459
1460
        return $record->$fieldName;
1461
    }
1462
1463
    public function getManipulatedList(): SS_List
1464
    {
1465
        return $this->list;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->list could return the type null which is incompatible with the type-hinted return SilverStripe\ORM\SS_List. Consider adding an additional type-check to rule them out.
Loading history...
1466
    }
1467
1468
    public function getList(): SS_List
1469
    {
1470
        return $this->list;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->list could return the type null which is incompatible with the type-hinted return SilverStripe\ORM\SS_List. Consider adding an additional type-check to rule them out.
Loading history...
1471
    }
1472
1473
    public function setList(SS_List $list): self
1474
    {
1475
        if ($this->autoloadDataList && $list instanceof DataList) {
1476
            $this->wizardRemotePagination();
1477
        }
1478
        $this->list = $list;
1479
        return $this;
1480
    }
1481
1482
    public function hasArrayList(): bool
1483
    {
1484
        return $this->list instanceof ArrayList;
1485
    }
1486
1487
    public function getArrayList(): ArrayList
1488
    {
1489
        if (!$this->list instanceof ArrayList) {
1490
            throw new RuntimeException("Value is not a ArrayList, it is a: " . get_class($this->list));
0 ignored issues
show
Bug introduced by
It seems like $this->list can also be of type null; however, parameter $object of get_class() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1490
            throw new RuntimeException("Value is not a ArrayList, it is a: " . get_class(/** @scrutinizer ignore-type */ $this->list));
Loading history...
1491
        }
1492
        return $this->list;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->list returns the type null which is incompatible with the type-hinted return SilverStripe\ORM\ArrayList.
Loading history...
1493
    }
1494
1495
    public function hasDataList(): bool
1496
    {
1497
        return $this->list instanceof DataList;
1498
    }
1499
1500
    /**
1501
     * A properly typed on which you can call byID
1502
     * @return ArrayList|DataList
1503
     */
1504
    public function getByIDList()
1505
    {
1506
        return $this->list;
1507
    }
1508
1509
    public function hasByIDList(): bool
1510
    {
1511
        return $this->hasDataList() || $this->hasArrayList();
1512
    }
1513
1514
    public function getDataList(): DataList
1515
    {
1516
        if (!$this->list instanceof DataList) {
1517
            throw new RuntimeException("Value is not a DataList, it is a: " . get_class($this->list));
0 ignored issues
show
Bug introduced by
It seems like $this->list can also be of type null; however, parameter $object of get_class() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1517
            throw new RuntimeException("Value is not a DataList, it is a: " . get_class(/** @scrutinizer ignore-type */ $this->list));
Loading history...
1518
        }
1519
        return $this->list;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->list returns the type null which is incompatible with the type-hinted return SilverStripe\ORM\DataList.
Loading history...
1520
    }
1521
1522
    public function getManipulatedData(int $limit, int $offset, array $sort = null, array $filter = null): array
1523
    {
1524
        if (!$this->hasDataList()) {
1525
            $data = $this->list->toNestedArray();
0 ignored issues
show
Bug introduced by
The method toNestedArray() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1525
            /** @scrutinizer ignore-call */ 
1526
            $data = $this->list->toNestedArray();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1526
1527
            $lastRow = $this->list->count();
1528
            $lastPage = ceil($lastRow / $limit);
1529
1530
            $result = [
1531
                'last_row' => $lastRow,
1532
                'last_page' => $lastPage,
1533
                'data' => $data,
1534
            ];
1535
1536
            return $result;
1537
        }
1538
1539
        $dataList = $this->getDataList();
1540
1541
        $schema = DataObject::getSchema();
1542
        $dataClass = $dataList->dataClass();
1543
1544
        /** @var DataObject $singleton */
1545
        $singleton = singleton($dataClass);
1546
        $resolutionMap = [];
1547
1548
        $sortSql = [];
1549
        if ($sort) {
1550
            foreach ($sort as $sortValues) {
1551
                $cols = array_keys($this->columns);
1552
                $field = $sortValues['field'];
1553
                if (!in_array($field, $cols)) {
1554
                    throw new Exception("Invalid sort field: $field");
1555
                }
1556
                $dir = $sortValues['dir'];
1557
                if (!in_array($dir, ['asc', 'desc'])) {
1558
                    throw new Exception("Invalid sort dir: $dir");
1559
                }
1560
1561
                // Nested sort
1562
                if (strpos($field, '.') !== false) {
1563
                    $parts = explode(".", $field);
1564
1565
                    // Resolve relation only once in case of multiples similar keys
1566
                    if (!isset($resolutionMap[$parts[0]])) {
1567
                        $resolutionMap[$parts[0]] = $singleton->relObject($parts[0]);
1568
                    }
1569
                    // Not matching anything (maybe a formatting .Nice ?)
1570
                    if (!$resolutionMap[$parts[0]] || !($resolutionMap[$parts[0]] instanceof DataList)) {
1571
                        $field = $parts[0];
0 ignored issues
show
Unused Code introduced by
The assignment to $field is dead and can be removed.
Loading history...
1572
                        continue;
1573
                    }
1574
                    $relatedObject = get_class($resolutionMap[$parts[0]]);
1575
                    $tableName = $schema->tableForField($relatedObject, $parts[1]);
1576
                    $baseIDColumn = $schema->sqlColumnForField($dataClass, 'ID');
1577
                    $tableAlias = $parts[0];
1578
                    $dataList = $dataList->leftJoin($tableName, "\"{$tableAlias}\".\"ID\" = {$baseIDColumn}", $tableAlias);
1579
                }
1580
1581
                $sortSql[] = $field . ' ' . $dir;
1582
            }
1583
        } else {
1584
            // If we have a sort column
1585
            if (isset($this->columns[self::UI_SORT])) {
1586
                $sortSql[] = $this->columns[self::UI_SORT]['field'] . ' ASC';
1587
            }
1588
        }
1589
        if (!empty($sortSql)) {
1590
            $dataList = $dataList->sort(implode(", ", $sortSql));
1591
        }
1592
1593
        // Filtering is an array of field/type/value arrays
1594
        $where = [];
1595
        $anyWhere = [];
1596
        if ($filter) {
1597
            foreach ($filter as $filterValues) {
1598
                $cols = array_keys($this->columns);
1599
                $field = $filterValues['field'];
1600
                if (strpos($field, '__') !== 0 && !in_array($field, $cols)) {
1601
                    throw new Exception("Invalid filter field: $field");
1602
                }
1603
                $value = $filterValues['value'];
1604
                $type = $filterValues['type'];
1605
1606
                $rawValue = $value;
1607
1608
                // Strict value
1609
                if ($value === "true") {
1610
                    $value = true;
1611
                } elseif ($value === "false") {
1612
                    $value = false;
1613
                }
1614
1615
                switch ($type) {
1616
                    case "=":
1617
                        if ($field === "__wildcard") {
1618
                            // It's a wildcard search
1619
                            $anyWhere = $this->createWildcardFilters($rawValue);
1620
                        } elseif ($field === "__quickfilter") {
1621
                            // It's a quickfilter search
1622
                            $this->createQuickFilter($rawValue, $dataList);
1623
                        } else {
1624
                            $where["$field"] = $value;
1625
                        }
1626
                        break;
1627
                    case "!=":
1628
                        $where["$field:not"] = $value;
1629
                        break;
1630
                    case "like":
1631
                        $where["$field:PartialMatch:nocase"] = $value;
1632
                        break;
1633
                    case "keywords":
1634
                        $where["$field:PartialMatch:nocase"] = str_replace(" ", "%", $value);
1635
                        break;
1636
                    case "starts":
1637
                        $where["$field:StartsWith:nocase"] = $value;
1638
                        break;
1639
                    case "ends":
1640
                        $where["$field:EndsWith:nocase"] = $value;
1641
                        break;
1642
                    case "<":
1643
                        $where["$field:LessThan:nocase"] = $value;
1644
                        break;
1645
                    case "<=":
1646
                        $where["$field:LessThanOrEqual:nocase"] = $value;
1647
                        break;
1648
                    case ">":
1649
                        $where["$field:GreaterThan:nocase"] = $value;
1650
                        break;
1651
                    case ">=":
1652
                        $where["$field:GreaterThanOrEqual:nocase"] = $value;
1653
                        break;
1654
                    case "in":
1655
                        $where["$field"] = $value;
1656
                        break;
1657
                    case "regex":
1658
                        $dataList = $dataList->where('REGEXP ' . Convert::raw2sql($value));
1659
                        break;
1660
                    default:
1661
                        throw new Exception("Invalid sort dir: $dir");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dir does not seem to be defined for all execution paths leading up to this point.
Loading history...
1662
                }
1663
            }
1664
        }
1665
        if (!empty($where)) {
1666
            $dataList = $dataList->filter($where);
1667
        }
1668
        if (!empty($anyWhere)) {
1669
            $dataList = $dataList->filterAny($anyWhere);
1670
        }
1671
1672
        $lastRow = $dataList->count();
1673
        $lastPage = ceil($lastRow / $limit);
1674
1675
        $data = [];
1676
        /** @var DataObject $record */
1677
        foreach ($dataList->limit($limit, $offset) as $record) {
1678
            if ($record->hasMethod('canView') && !$record->canView()) {
1679
                continue;
1680
            }
1681
1682
            $item = [
1683
                'ID' => $record->ID,
1684
            ];
1685
1686
            // Add row class
1687
            if ($record->hasMethod('TabulatorRowClass')) {
1688
                $item['_class'] = $record->TabulatorRowClass();
1689
            } elseif ($record->hasMethod('getRowClass')) {
1690
                $item['_class'] = $record->getRowClass();
1691
            }
1692
            // Add row color
1693
            if ($record->hasMethod('TabulatorRowColor')) {
1694
                $item['_color'] = $record->TabulatorRowColor();
1695
            }
1696
1697
            $nested = [];
1698
            foreach ($this->columns as $col) {
1699
                // UI field are skipped
1700
                if (empty($col['field'])) {
1701
                    continue;
1702
                }
1703
1704
                $field = $col['field'];
1705
1706
                // Explode relations or formatters
1707
                if (strpos($field, '.') !== false) {
1708
                    $parts = explode('.', $field);
1709
                    $classOrField = $parts[0];
1710
                    $relationOrMethod = $parts[1];
1711
                    // For relations, like Users.count
1712
                    if ($singleton->getRelationClass($classOrField)) {
1713
                        $nested[$classOrField][] = $relationOrMethod;
1714
                        continue;
1715
                    } else {
1716
                        // For fields, like SomeValue.Nice
1717
                        $dbObject = $record->dbObject($classOrField);
1718
                        if ($dbObject) {
1719
                            $item[$classOrField] = [
1720
                                $relationOrMethod => $dbObject->$relationOrMethod()
1721
                            ];
1722
                            continue;
1723
                        }
1724
                    }
1725
                }
1726
1727
                // Do not override already set fields
1728
                if (!isset($item[$field])) {
1729
                    $getField = 'get' . ucfirst($field);
1730
1731
                    if ($record->hasMethod($getField)) {
1732
                        // Prioritize getXyz method
1733
                        $item[$field] = $record->$getField();
1734
                    } elseif ($record->hasMethod($field)) {
1735
                        // Regular xyz method method
1736
                        $item[$field] = $record->$field();
1737
                    } else {
1738
                        // Field
1739
                        $item[$field] = $record->getField($field);
1740
                    }
1741
                }
1742
            }
1743
            // Fill in nested data, like Users.count
1744
            foreach ($nested as $nestedClass => $nestedColumns) {
1745
                /** @var DataObject $relObject */
1746
                $relObject = $record->relObject($nestedClass);
1747
                $nestedData = [];
1748
                foreach ($nestedColumns as $nestedColumn) {
1749
                    $nestedData[$nestedColumn] = $this->getDataFieldValue($relObject, $nestedColumn);
1750
                }
1751
                $item[$nestedClass] = $nestedData;
1752
            }
1753
            $data[] = $item;
1754
        }
1755
1756
        $result = [
1757
            'last_row' => $lastRow,
1758
            'last_page' => $lastPage,
1759
            'data' => $data,
1760
        ];
1761
1762
        if (Director::isDev()) {
1763
            $result['sql'] = $dataList->sql();
1764
        }
1765
1766
        return $result;
1767
    }
1768
1769
    public function QuickFiltersList()
1770
    {
1771
        $current = $this->StateValue('filter', '__quickfilter');
1772
        $list = new ArrayList();
1773
        foreach ($this->quickFilters as $k => $v) {
1774
            $list->push([
1775
                'Value' => $k,
1776
                'Label' => $v['label'],
1777
                'Selected' => $k == $current
1778
            ]);
1779
        }
1780
        return $list;
1781
    }
1782
1783
    protected function createQuickFilter($filter, &$list)
1784
    {
1785
        $qf = $this->quickFilters[$filter] ?? null;
1786
        if (!$qf) {
1787
            return;
1788
        }
1789
1790
        $callback = $qf['callback'] ?? null;
1791
        if (!$callback) {
1792
            return;
1793
        }
1794
1795
        $callback($list);
1796
    }
1797
1798
    protected function createWildcardFilters(string $value)
1799
    {
1800
        $wildcardFields = $this->wildcardFields;
1801
1802
        // Create from model
1803
        if (empty($wildcardFields)) {
1804
            /** @var DataObject $singl */
1805
            $singl = singleton($this->modelClass);
1806
            $searchableFields = $singl->searchableFields();
1807
1808
            foreach ($searchableFields as $k => $v) {
1809
                $general = $v['general'] ?? true;
1810
                if (!$general) {
1811
                    continue;
1812
                }
1813
                $wildcardFields[] = $k;
1814
            }
1815
        }
1816
1817
        // Queries can have the format s:... or e:... or =:.... or %:....
1818
        $filter = $this->defaultFilter;
1819
        if (strpos($value, ':') === 1) {
1820
            $parts = explode(":", $value);
1821
            $shortcut = array_shift($parts);
1822
            $value = implode(":", $parts);
1823
            switch ($shortcut) {
1824
                case 's':
1825
                    $filter = 'StartsWith';
1826
                    break;
1827
                case 'e':
1828
                    $filter = 'EndsWith';
1829
                    break;
1830
                case '=':
1831
                    $filter = 'ExactMatch';
1832
                    break;
1833
                case '%':
1834
                    $filter = 'PartialMatch';
1835
                    break;
1836
            }
1837
        }
1838
1839
        // Process value
1840
        $baseValue = $value;
1841
        $value = str_replace(" ", "%", $value);
1842
        $value = str_replace(['.', '_', '-'], ' ', $value);
1843
1844
        // Create filters
1845
        $anyWhere = [];
1846
        foreach ($wildcardFields as $f) {
1847
            if (!$value) {
1848
                continue;
1849
            }
1850
            $key = $f . ":" . $filter;
1851
            $anyWhere[$key] = $value;
1852
1853
            // also look on unfiltered data
1854
            if ($value != $baseValue) {
1855
                $anyWhere[$key] = $baseValue;
1856
            }
1857
        }
1858
1859
        return $anyWhere;
1860
    }
1861
1862
    public function getModelClass(): ?string
1863
    {
1864
        if ($this->modelClass) {
1865
            return $this->modelClass;
1866
        }
1867
        if ($this->list && $this->list instanceof DataList) {
1868
            return $this->list->dataClass();
1869
        }
1870
        return null;
1871
    }
1872
1873
    public function setModelClass(string $modelClass): self
1874
    {
1875
        $this->modelClass = $modelClass;
1876
        return $this;
1877
    }
1878
1879
1880
    public function getDataAttribute(string $k)
1881
    {
1882
        if (isset($this->dataAttributes[$k])) {
1883
            return $this->dataAttributes[$k];
1884
        }
1885
        return $this->getAttribute("data-$k");
1886
    }
1887
1888
    public function setDataAttribute(string $k, $v): self
1889
    {
1890
        $this->dataAttributes[$k] = $v;
1891
        return $this;
1892
    }
1893
1894
    public function dataAttributesHTML(): string
1895
    {
1896
        $parts = [];
1897
        foreach ($this->dataAttributes as $k => $v) {
1898
            if (!$v) {
1899
                continue;
1900
            }
1901
            if (is_array($v)) {
1902
                $v = json_encode($v);
1903
            }
1904
            $parts[] = "data-$k='$v'";
1905
        }
1906
        return implode(" ", $parts);
1907
    }
1908
1909
    protected function processLink(string $url): string
1910
    {
1911
        // It's not necessary to process
1912
        if ($url == '#') {
1913
            return $url;
1914
        }
1915
        // It's a temporary link on the form
1916
        if (strpos($url, 'form:') === 0) {
1917
            return $this->Link(preg_replace('/^form:/', '', $url));
1918
        }
1919
        // It's a temporary link on the controller
1920
        if (strpos($url, 'controller:') === 0) {
1921
            return $this->ControllerLink(preg_replace('/^controller:/', '', $url));
1922
        }
1923
        // It's a custom protocol (mailto: etc)
1924
        if (strpos($url, ':') !== false) {
1925
            return $url;
1926
        }
1927
        return $url;
1928
    }
1929
1930
    protected function processLinks(): void
1931
    {
1932
        // Process editor and formatter links
1933
        foreach ($this->columns as $name => $params) {
1934
            if (!empty($params['formatterParams']['url'])) {
1935
                $url = $this->processLink($params['formatterParams']['url']);
1936
                $this->columns[$name]['formatterParams']['url'] = $url;
1937
            }
1938
            if (!empty($params['editorParams']['url'])) {
1939
                $url = $this->processLink($params['editorParams']['url']);
1940
                $this->columns[$name]['editorParams']['url'] = $url;
1941
            }
1942
            // Set valuesURL automatically if not already set
1943
            if (!empty($params['editorParams']['autocomplete'])) {
1944
                if (empty($params['editorParams']['valuesURL'])) {
1945
                    $params = [
1946
                        'Column' => $name,
1947
                        'SecurityID' => SecurityToken::getSecurityID(),
1948
                    ];
1949
                    $url = $this->Link('autocomplete') . '?' . http_build_query($params);
1950
                    $this->columns[$name]['editorParams']['valuesURL'] = $url;
1951
                    $this->columns[$name]['editorParams']['filterRemote'] = true;
1952
                }
1953
            }
1954
        }
1955
1956
        // Other links
1957
        $url = $this->getOption('ajaxURL');
1958
        if ($url) {
1959
            $this->setOption('ajaxURL', $this->processLink($url));
1960
        }
1961
    }
1962
1963
    /**
1964
     * @link https://github.com/lekoala/formidable-elements/blob/master/src/classes/tabulator/Format/formatters/button.js
1965
     */
1966
    public function makeButton(string $urlOrAction, string $icon, string $title): array
1967
    {
1968
        $opts = [
1969
            "responsive" => 0,
1970
            "cssClass" => 'tabulator-cell-btn',
1971
            "tooltip" => $title,
1972
            "formatter" => "button",
1973
            "formatterParams" => [
1974
                "icon" => $icon,
1975
                "title" => $title,
1976
                "url" => $this->TempLink($urlOrAction), // On the controller by default
1977
            ],
1978
            "cellClick" => ["__fn" => "SSTabulator.buttonHandler"],
1979
            // We need to force its size otherwise Tabulator will assign too much space
1980
            "width" => 36 + strlen($title) * 12,
1981
            "hozAlign" => "center",
1982
            "headerSort" => false,
1983
        ];
1984
        return $opts;
1985
    }
1986
1987
    public function addButtonFromArray(string $action, array $opts = [], string $before = null): self
1988
    {
1989
        // Insert before given column
1990
        if ($before) {
1991
            $this->addColumnBefore("action_$action", $opts, $before);
1992
        } else {
1993
            $this->columns["action_$action"] = $opts;
1994
        }
1995
        return $this;
1996
    }
1997
1998
    /**
1999
     * @param string $action Action name
2000
     * @param string $url Parameters between {} will be interpolated by row values.
2001
     * @param string $icon
2002
     * @param string $title
2003
     * @param string|null $before
2004
     * @return self
2005
     */
2006
    public function addButton(string $action, string $url, string $icon, string $title, string $before = null): self
2007
    {
2008
        $opts = $this->makeButton($url, $icon, $title);
2009
        $this->addButtonFromArray($action, $opts, $before);
2010
        return $this;
2011
    }
2012
2013
    public function shiftButton(string $action, string $url, string $icon, string $title): self
2014
    {
2015
        // Find first action
2016
        foreach ($this->columns as $name => $options) {
2017
            if (strpos($name, 'action_') === 0) {
2018
                return $this->addButton($action, $url, $icon, $title, $name);
2019
            }
2020
        }
2021
        return $this->addButton($action, $url, $icon, $title);
2022
    }
2023
2024
    public function getActions(): array
2025
    {
2026
        $cols = [];
2027
        foreach ($this->columns as $name => $options) {
2028
            if (strpos($name, 'action_') === 0) {
2029
                $cols[$name] = $options;
2030
            }
2031
        }
2032
        return $cols;
2033
    }
2034
2035
    public function getUiColumns(): array
2036
    {
2037
        $cols = [];
2038
        foreach ($this->columns as $name => $options) {
2039
            if (strpos($name, 'ui_') === 0) {
2040
                $cols[$name] = $options;
2041
            }
2042
        }
2043
        return $cols;
2044
    }
2045
2046
    public function getSystemColumns(): array
2047
    {
2048
        return array_merge($this->getActions(), $this->getUiColumns());
2049
    }
2050
2051
    public function removeButton(string $action): self
2052
    {
2053
        if ($this->hasButton($action)) {
2054
            unset($this->columns["action_$action"]);
2055
        }
2056
        return $this;
2057
    }
2058
2059
    public function hasButton(string $action): bool
2060
    {
2061
        return isset($this->columns["action_$action"]);
2062
    }
2063
2064
    /**
2065
     * @link http://www.tabulator.info/docs/5.5/columns#definition
2066
     * @param string $field (Required) this is the key for this column in the data array
2067
     * @param string $title (Required) This is the title that will be displayed in the header for this column
2068
     * @param array $opts Other options to merge in
2069
     * @return $this
2070
     */
2071
    public function addColumn(string $field, string $title = null, array $opts = []): self
2072
    {
2073
        if ($title === null) {
2074
            $title = $field;
2075
        }
2076
2077
        $baseOpts = [
2078
            "field" => $field,
2079
            "title" => $title,
2080
        ];
2081
2082
        if (!empty($opts)) {
2083
            $baseOpts = array_merge($baseOpts, $opts);
2084
        }
2085
2086
        $this->columns[$field] = $baseOpts;
2087
        return $this;
2088
    }
2089
2090
    /**
2091
     * @link http://www.tabulator.info/docs/5.5/columns#definition
2092
     * @param array $opts Other options to merge in
2093
     * @param ?string $before
2094
     * @return $this
2095
     */
2096
    public function addColumnFromArray(array $opts = [], $before = null)
2097
    {
2098
        if (empty($opts['field']) || !isset($opts['title'])) {
2099
            throw new Exception("Missing field or title key");
2100
        }
2101
        $field = $opts['field'];
2102
2103
        if ($before) {
2104
            $this->addColumnBefore($field, $opts, $before);
2105
        } else {
2106
            $this->columns[$field] = $opts;
2107
        }
2108
2109
        return $this;
2110
    }
2111
2112
    protected function addColumnBefore($field, $opts, $before)
2113
    {
2114
        if (array_key_exists($before, $this->columns)) {
2115
            $new = [];
2116
            foreach ($this->columns as $k => $value) {
2117
                if ($k === $before) {
2118
                    $new[$field] = $opts;
2119
                }
2120
                $new[$k] = $value;
2121
            }
2122
            $this->columns = $new;
2123
        }
2124
    }
2125
2126
    public function makeColumnEditable(string $field, string $editor = "input", array $params = [])
2127
    {
2128
        $col = $this->getColumn($field);
2129
        if (!$col) {
2130
            throw new InvalidArgumentException("$field is not a valid column");
2131
        }
2132
2133
        switch ($editor) {
2134
            case 'date':
2135
                $editor = "input";
2136
                $params = [
2137
                    'mask' => "9999-99-99",
2138
                    'maskAutoFill' => 'true',
2139
                ];
2140
                break;
2141
            case 'datetime':
2142
                $editor = "input";
2143
                $params = [
2144
                    'mask' => "9999-99-99 99:99:99",
2145
                    'maskAutoFill' => 'true',
2146
                ];
2147
                break;
2148
        }
2149
2150
        if (empty($col['cssClass'])) {
2151
            $col['cssClass'] = 'no-change-track';
2152
        } else {
2153
            $col['cssClass'] .= ' no-change-track';
2154
        }
2155
2156
        $col['editor'] = $editor;
2157
        $col['editorParams'] = $params;
2158
        if ($editor == "list") {
2159
            if (!empty($params['autocomplete'])) {
2160
                $col['headerFilter'] = "input"; // force input
2161
            } else {
2162
                $col['headerFilterParams'] = $params; // editor is used as base filter editor
2163
            }
2164
        }
2165
2166
2167
        $this->setColumn($field, $col);
2168
    }
2169
2170
    /**
2171
     * Get column details
2172
2173
     * @param string $key
2174
     */
2175
    public function getColumn(string $key): ?array
2176
    {
2177
        if (isset($this->columns[$key])) {
2178
            return $this->columns[$key];
2179
        }
2180
        return null;
2181
    }
2182
2183
    /**
2184
     * Set column details
2185
     *
2186
     * @param string $key
2187
     * @param array $col
2188
     */
2189
    public function setColumn(string $key, array $col): self
2190
    {
2191
        $this->columns[$key] = $col;
2192
        return $this;
2193
    }
2194
2195
    /**
2196
     * Update column details
2197
     *
2198
     * @param string $key
2199
     * @param array $col
2200
     */
2201
    public function updateColumn(string $key, array $col): self
2202
    {
2203
        $data = $this->getColumn($key);
2204
        if ($data) {
2205
            $this->setColumn($key, array_merge($data, $col));
2206
        }
2207
        return $this;
2208
    }
2209
2210
    /**
2211
     * Remove a column
2212
     *
2213
     * @param string $key
2214
     */
2215
    public function removeColumn(string $key): void
2216
    {
2217
        unset($this->columns[$key]);
2218
    }
2219
2220
2221
    /**
2222
     * Get the value of columns
2223
     */
2224
    public function getColumns(): array
2225
    {
2226
        return $this->columns;
2227
    }
2228
2229
    /**
2230
     * Set the value of columns
2231
     */
2232
    public function setColumns(array $columns): self
2233
    {
2234
        $this->columns = $columns;
2235
        return $this;
2236
    }
2237
2238
    public function clearColumns(bool $keepSystem = true): void
2239
    {
2240
        $sysNames = array_keys($this->getSystemColumns());
2241
        foreach ($this->columns as $k => $v) {
2242
            if ($keepSystem && in_array($k, $sysNames)) {
2243
                continue;
2244
            }
2245
            $this->removeColumn($k);
2246
        }
2247
    }
2248
2249
    /**
2250
     * This should be the rough equivalent to GridFieldDataColumns::getDisplayFields
2251
     */
2252
    public function getDisplayFields(): array
2253
    {
2254
        $fields = [];
2255
        foreach ($this->columns as $col) {
2256
            if (empty($col['field'])) {
2257
                continue;
2258
            }
2259
            $fields[$col['field']] = $col['title'];
2260
        }
2261
        return $fields;
2262
    }
2263
2264
    /**
2265
     * This should be the rough equivalent to GridFieldDataColumns::setDisplayFields
2266
     */
2267
    public function setDisplayFields(array $arr): void
2268
    {
2269
        $this->clearColumns();
2270
        $actions = array_keys($this->getActions());
2271
        $before = $actions[0] ?? null;
2272
        foreach ($arr as $k => $v) {
2273
            $this->addColumnFromArray([
2274
                'field' => $k,
2275
                'title' => $v,
2276
            ], $before);
2277
        }
2278
    }
2279
2280
    /**
2281
     * Convenience method that get/set fields
2282
     */
2283
    public function addDisplayFields(array $arr): void
2284
    {
2285
        $fields = $this->getDisplayFields();
2286
        $fields = array_merge($fields, $arr);
2287
        $this->setDisplayFields($fields);
2288
    }
2289
2290
    /**
2291
     * @param string|AbstractTabulatorTool $tool Pass name or class
2292
     * @return AbstractTabulatorTool|null
2293
     */
2294
    public function getTool($tool): ?AbstractTabulatorTool
2295
    {
2296
        if (is_object($tool)) {
2297
            $tool = get_class($tool);
2298
        }
2299
        if (!is_string($tool)) {
0 ignored issues
show
introduced by
The condition is_string($tool) is always true.
Loading history...
2300
            throw new InvalidArgumentException('Tool must be an object or a class name');
2301
        }
2302
        foreach ($this->tools as $t) {
2303
            if ($t['name'] === $tool) {
2304
                return $t['tool'];
2305
            }
2306
            if ($t['tool'] instanceof $tool) {
2307
                return $t['tool'];
2308
            }
2309
        }
2310
        return null;
2311
    }
2312
2313
    /**
2314
     * @param string $pos start|end
2315
     * @param AbstractTabulatorTool $tool
2316
     * @param string $name
2317
     * @return self
2318
     */
2319
    public function addTool(string $pos, AbstractTabulatorTool $tool, string $name = ''): self
2320
    {
2321
        $tool->setTabulatorGrid($this);
2322
        if ($tool->getName() && !$name) {
2323
            $name = $tool->getName();
2324
        }
2325
        $tool->setName($name);
2326
2327
        $this->tools[] = [
2328
            'position' => $pos,
2329
            'tool' => $tool,
2330
            'name' => $name,
2331
        ];
2332
        return $this;
2333
    }
2334
2335
    public function addToolStart(AbstractTabulatorTool $tool, string $name = ''): self
2336
    {
2337
        return $this->addTool(self::POS_START, $tool, $name);
2338
    }
2339
2340
    public function addToolEnd(AbstractTabulatorTool $tool, string $name = ''): self
2341
    {
2342
        return $this->addTool(self::POS_END, $tool, $name);
2343
    }
2344
2345
    public function removeTool($toolName): self
2346
    {
2347
        if (is_object($toolName)) {
2348
            $toolName = get_class($toolName);
2349
        }
2350
        if (!is_string($toolName)) {
2351
            throw new InvalidArgumentException('Tool must be an object or a class name');
2352
        }
2353
        foreach ($this->tools as $idx => $tool) {
2354
            if ($tool['name'] === $toolName) {
2355
                unset($this->tools[$idx]);
2356
            }
2357
            if (class_exists($toolName) && $tool['tool'] instanceof $toolName) {
2358
                unset($this->tools[$idx]);
2359
            }
2360
        }
2361
        return $this;
2362
    }
2363
2364
    /**
2365
     * @param string|AbstractBulkAction $bulkAction Pass name or class
2366
     * @return AbstractBulkAction|null
2367
     */
2368
    public function getBulkAction($bulkAction): ?AbstractBulkAction
2369
    {
2370
        if (is_object($bulkAction)) {
2371
            $bulkAction = get_class($bulkAction);
2372
        }
2373
        if (!is_string($bulkAction)) {
0 ignored issues
show
introduced by
The condition is_string($bulkAction) is always true.
Loading history...
2374
            throw new InvalidArgumentException('BulkAction must be an object or a class name');
2375
        }
2376
        foreach ($this->bulkActions as $ba) {
2377
            if ($ba->getName() == $bulkAction) {
2378
                return $ba;
2379
            }
2380
            if ($ba instanceof $bulkAction) {
2381
                return $ba;
2382
            }
2383
        }
2384
        return null;
2385
    }
2386
2387
    public function getBulkActions(): array
2388
    {
2389
        return $this->bulkActions;
2390
    }
2391
2392
    /**
2393
     * @param AbstractBulkAction[] $bulkActions
2394
     * @return self
2395
     */
2396
    public function setBulkActions(array $bulkActions): self
2397
    {
2398
        foreach ($bulkActions as $bulkAction) {
2399
            $bulkAction->setTabulatorGrid($this);
2400
        }
2401
        $this->bulkActions = $bulkActions;
2402
        return $this;
2403
    }
2404
2405
    /**
2406
     * If you didn't before, you probably want to call wizardSelectable
2407
     * to get the actual selection checkbox too
2408
     *
2409
     * @param AbstractBulkAction $handler
2410
     * @return self
2411
     */
2412
    public function addBulkAction(AbstractBulkAction $handler): self
2413
    {
2414
        $handler->setTabulatorGrid($this);
2415
2416
        $this->bulkActions[] = $handler;
2417
        return $this;
2418
    }
2419
2420
    public function removeBulkAction($bulkAction): self
2421
    {
2422
        if (is_object($bulkAction)) {
2423
            $bulkAction = get_class($bulkAction);
2424
        }
2425
        if (!is_string($bulkAction)) {
2426
            throw new InvalidArgumentException('Bulk action must be an object or a class name');
2427
        }
2428
        foreach ($this->bulkActions as $idx => $ba) {
2429
            if ($ba->getName() == $bulkAction) {
2430
                unset($this->bulkAction[$idx]);
0 ignored issues
show
Bug Best Practice introduced by
The property bulkAction does not exist on LeKoala\Tabulator\TabulatorGrid. Since you implemented __get, consider adding a @property annotation.
Loading history...
2431
            }
2432
            if ($ba instanceof $bulkAction) {
2433
                unset($this->bulkAction[$idx]);
2434
            }
2435
        }
2436
        return $this;
2437
    }
2438
2439
    public function getColumnDefault(string $opt)
2440
    {
2441
        return $this->columnDefaults[$opt] ?? null;
2442
    }
2443
2444
    public function setColumnDefault(string $opt, $value)
2445
    {
2446
        $this->columnDefaults[$opt] = $value;
2447
    }
2448
2449
    public function getColumnDefaults(): array
2450
    {
2451
        return $this->columnDefaults;
2452
    }
2453
2454
    public function setColumnDefaults(array $columnDefaults): self
2455
    {
2456
        $this->columnDefaults = $columnDefaults;
2457
        return $this;
2458
    }
2459
2460
    public function getListeners(): array
2461
    {
2462
        return $this->listeners;
2463
    }
2464
2465
    public function setListeners(array $listeners): self
2466
    {
2467
        $this->listeners = $listeners;
2468
        return $this;
2469
    }
2470
2471
    public function addListener(string $event, string $functionName): self
2472
    {
2473
        $this->listeners[$event] = $functionName;
2474
        return $this;
2475
    }
2476
2477
    public function removeListener(string $event): self
2478
    {
2479
        if (isset($this->listeners[$event])) {
2480
            unset($this->listeners[$event]);
2481
        }
2482
        return $this;
2483
    }
2484
2485
    public function getLinksOptions(): array
2486
    {
2487
        return $this->linksOptions;
2488
    }
2489
2490
    public function setLinksOptions(array $linksOptions): self
2491
    {
2492
        $this->linksOptions = $linksOptions;
2493
        return $this;
2494
    }
2495
2496
    public function registerLinkOption(string $linksOption): self
2497
    {
2498
        $this->linksOptions[] = $linksOption;
2499
        return $this;
2500
    }
2501
2502
    public function unregisterLinkOption(string $linksOption): self
2503
    {
2504
        $this->linksOptions = array_diff($this->linksOptions, [$linksOption]);
2505
        return $this;
2506
    }
2507
2508
    /**
2509
     * Get the value of pageSize
2510
     */
2511
    public function getPageSize(): int
2512
    {
2513
        return $this->pageSize;
2514
    }
2515
2516
    /**
2517
     * Set the value of pageSize
2518
     *
2519
     * @param int $pageSize
2520
     */
2521
    public function setPageSize(int $pageSize): self
2522
    {
2523
        $this->pageSize = $pageSize;
2524
        return $this;
2525
    }
2526
2527
    /**
2528
     * Get the value of autoloadDataList
2529
     */
2530
    public function getAutoloadDataList(): bool
2531
    {
2532
        return $this->autoloadDataList;
2533
    }
2534
2535
    /**
2536
     * Set the value of autoloadDataList
2537
     *
2538
     * @param bool $autoloadDataList
2539
     */
2540
    public function setAutoloadDataList(bool $autoloadDataList): self
2541
    {
2542
        $this->autoloadDataList = $autoloadDataList;
2543
        return $this;
2544
    }
2545
2546
    /**
2547
     * Set the value of itemRequestClass
2548
     */
2549
    public function setItemRequestClass(string $itemRequestClass): self
2550
    {
2551
        $this->itemRequestClass = $itemRequestClass;
2552
        return $this;
2553
    }
2554
2555
    /**
2556
     * Get the value of lazyInit
2557
     */
2558
    public function getLazyInit(): bool
2559
    {
2560
        return $this->lazyInit;
2561
    }
2562
2563
    /**
2564
     * Set the value of lazyInit
2565
     */
2566
    public function setLazyInit(bool $lazyInit): self
2567
    {
2568
        $this->lazyInit = $lazyInit;
2569
        return $this;
2570
    }
2571
2572
    /**
2573
     * Get the value of rowClickTriggersAction
2574
     */
2575
    public function getRowClickTriggersAction(): bool
2576
    {
2577
        return $this->rowClickTriggersAction;
2578
    }
2579
2580
    /**
2581
     * Set the value of rowClickTriggersAction
2582
     */
2583
    public function setRowClickTriggersAction(bool $rowClickTriggersAction): self
2584
    {
2585
        $this->rowClickTriggersAction = $rowClickTriggersAction;
2586
        return $this;
2587
    }
2588
2589
    /**
2590
     * Get the value of controllerFunction
2591
     */
2592
    public function getControllerFunction(): string
2593
    {
2594
        if (!$this->controllerFunction) {
2595
            return $this->getName() ?? "TabulatorGrid";
2596
        }
2597
        return $this->controllerFunction;
2598
    }
2599
2600
    /**
2601
     * Set the value of controllerFunction
2602
     */
2603
    public function setControllerFunction(string $controllerFunction): self
2604
    {
2605
        $this->controllerFunction = $controllerFunction;
2606
        return $this;
2607
    }
2608
2609
    /**
2610
     * Get the value of editUrl
2611
     */
2612
    public function getEditUrl(): string
2613
    {
2614
        return $this->editUrl;
2615
    }
2616
2617
    /**
2618
     * Set the value of editUrl
2619
     */
2620
    public function setEditUrl(string $editUrl): self
2621
    {
2622
        $this->editUrl = $editUrl;
2623
        return $this;
2624
    }
2625
2626
    /**
2627
     * Get the value of moveUrl
2628
     */
2629
    public function getMoveUrl(): string
2630
    {
2631
        return $this->moveUrl;
2632
    }
2633
2634
    /**
2635
     * Set the value of moveUrl
2636
     */
2637
    public function setMoveUrl(string $moveUrl): self
2638
    {
2639
        $this->moveUrl = $moveUrl;
2640
        return $this;
2641
    }
2642
2643
    /**
2644
     * Get the value of bulkUrl
2645
     */
2646
    public function getBulkUrl(): string
2647
    {
2648
        return $this->bulkUrl;
2649
    }
2650
2651
    /**
2652
     * Set the value of bulkUrl
2653
     */
2654
    public function setBulkUrl(string $bulkUrl): self
2655
    {
2656
        $this->bulkUrl = $bulkUrl;
2657
        return $this;
2658
    }
2659
2660
    /**
2661
     * Get the value of globalSearch
2662
     */
2663
    public function getGlobalSearch(): bool
2664
    {
2665
        return $this->globalSearch;
2666
    }
2667
2668
    /**
2669
     * Set the value of globalSearch
2670
     *
2671
     * @param bool $globalSearch
2672
     */
2673
    public function setGlobalSearch($globalSearch): self
2674
    {
2675
        $this->globalSearch = $globalSearch;
2676
        return $this;
2677
    }
2678
2679
    /**
2680
     * Get the value of wildcardFields
2681
     */
2682
    public function getWildcardFields(): array
2683
    {
2684
        return $this->wildcardFields;
2685
    }
2686
2687
    /**
2688
     * Set the value of wildcardFields
2689
     *
2690
     * @param array $wildcardFields
2691
     */
2692
    public function setWildcardFields($wildcardFields): self
2693
    {
2694
        $this->wildcardFields = $wildcardFields;
2695
        return $this;
2696
    }
2697
2698
    /**
2699
     * Get the value of quickFilters
2700
     */
2701
    public function getQuickFilters(): array
2702
    {
2703
        return $this->quickFilters;
2704
    }
2705
2706
    /**
2707
     * Pass an array with as a key, the name of the filter
2708
     * and as a value, an array with two keys: label and callback
2709
     *
2710
     * For example:
2711
     * 'myquickfilter' => [
2712
     *   'label' => 'My Quick Filter',
2713
     *   'callback' => function (&$list) {
2714
     *     ...
2715
     *   }
2716
     * ]
2717
     *
2718
     * @param array $quickFilters
2719
     */
2720
    public function setQuickFilters($quickFilters): self
2721
    {
2722
        $this->quickFilters = $quickFilters;
2723
        return $this;
2724
    }
2725
2726
    /**
2727
     * Get the value of groupLayout
2728
     */
2729
    public function getGroupLayout(): bool
2730
    {
2731
        return $this->groupLayout;
2732
    }
2733
2734
    /**
2735
     * Set the value of groupLayout
2736
     *
2737
     * @param bool $groupLayout
2738
     */
2739
    public function setGroupLayout($groupLayout): self
2740
    {
2741
        $this->groupLayout = $groupLayout;
2742
        return $this;
2743
    }
2744
2745
    /**
2746
     * Get the value of enableGridManipulation
2747
     */
2748
    public function getEnableGridManipulation(): bool
2749
    {
2750
        return $this->enableGridManipulation;
2751
    }
2752
2753
    /**
2754
     * Set the value of enableGridManipulation
2755
     *
2756
     * @param bool $enableGridManipulation
2757
     */
2758
    public function setEnableGridManipulation($enableGridManipulation): self
2759
    {
2760
        $this->enableGridManipulation = $enableGridManipulation;
2761
        return $this;
2762
    }
2763
2764
    /**
2765
     * Get the value of defaultFilter
2766
     */
2767
    public function getDefaultFilter(): string
2768
    {
2769
        return $this->defaultFilter;
2770
    }
2771
2772
    /**
2773
     * Set the value of defaultFilter
2774
     *
2775
     * @param string $defaultFilter
2776
     */
2777
    public function setDefaultFilter($defaultFilter): self
2778
    {
2779
        $this->defaultFilter = $defaultFilter;
2780
        return $this;
2781
    }
2782
}
2783