-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Lists.php
1851 lines (1591 loc) · 53.7 KB
/
Lists.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php namespace Backend\Widgets;
use Db;
use Str;
use Html;
use Lang;
use Backend;
use DbDongle;
use Carbon\Carbon;
use Winter\Storm\Html\Helper as HtmlHelper;
use Winter\Storm\Router\Helper as RouterHelper;
use System\Helpers\DateTime as DateTimeHelper;
use System\Classes\PluginManager;
use System\Classes\MediaLibrary;
use System\Classes\ImageResizer;
use Backend\Classes\ListColumn;
use Backend\Classes\WidgetBase;
use Winter\Storm\Database\Model;
use ApplicationException;
use BackendAuth;
/**
* List Widget
* Used for building back end lists, renders a list of model objects
*
* @package winter\wn-backend-module
* @author Alexey Bobkov, Samuel Georges
*/
class Lists extends WidgetBase
{
use Backend\Traits\PreferenceMaker;
//
// Configurable properties
//
/**
* @var array List column configuration.
*/
public $columns;
/**
* @var Model List model object.
*/
public $model;
/**
* @var string Link for each record row. Replace :id with the record id.
*/
public $recordUrl;
/**
* @var string Click event for each record row. Replace :id with the record id.
*/
public $recordOnClick;
/**
* @var string Message to display when there are no records in the list.
*/
public $noRecordsMessage = 'backend::lang.list.no_records';
/**
* @var int Maximum rows to display for each page.
*/
public $recordsPerPage;
/**
* @var array Options for number of items per page.
*/
public $perPageOptions;
/**
* @var bool Shows the sorting options for each column.
*/
public $showSorting = true;
/**
* @var mixed A default sort column to look for.
*/
public $defaultSort;
/**
* @var bool Display a checkbox next to each record row.
*/
public $showCheckboxes = false;
/**
* @var bool Display the list set up used for column visibility and ordering.
*/
public $showSetup = false;
/**
* @var bool Display parent/child relationships in the list.
*/
public $showTree = false;
/**
* @var bool Expand the tree nodes by default.
*/
public $treeExpanded = false;
/**
* @var bool|string Display pagination when limiting records per page.
*/
public $showPagination = 'auto';
/**
* @var bool Display page numbers with pagination, disable to improve performance.
*/
public $showPageNumbers = true;
/**
* @var string Specify a custom view path to override partials used by the list.
*/
public $customViewPath;
//
// Object properties
//
/**
* @inheritDoc
*/
protected $defaultAlias = 'list';
/**
* @var array Collection of all list columns used in this list.
* @see Backend\Classes\ListColumn
*/
protected $allColumns;
/**
* @var array Override default columns with supplied key names.
*/
protected $columnOverride;
/**
* @var array Columns to display and their order.
*/
protected $visibleColumns;
/**
* @var array Model data collection.
*/
protected $records;
/**
* @var int Current page number.
*/
protected $currentPageNumber;
/**
* @var string Filter the records by a search term.
*/
protected $searchTerm;
/**
* @var string If searching the records, specifies a policy to use.
* - all: result must contain all words
* - any: result can contain any word
* - exact: result must contain the exact phrase
*/
protected $searchMode;
/**
* @var string Use a custom scope method for performing searches.
*/
protected $searchScope;
/**
* @var array Collection of functions to apply to each list query.
*/
protected $filterCallbacks = [];
/**
* @var array All sortable columns.
*/
protected $sortableColumns;
/**
* @var string Sets the list sorting column.
*/
protected $sortColumn;
/**
* @var string Sets the list sorting direction (asc, desc)
*/
protected $sortDirection;
/**
* @var array List of CSS classes to apply to the list container element
*/
public $cssClasses = [];
/**
* Initialize the widget, called by the constructor and free from its parameters.
*/
public function init()
{
$this->fillFromConfig([
'columns',
'model',
'recordUrl',
'recordOnClick',
'noRecordsMessage',
'showPageNumbers',
'recordsPerPage',
'perPageOptions',
'showSorting',
'defaultSort',
'showCheckboxes',
'showSetup',
'showTree',
'treeExpanded',
'showPagination',
'customViewPath',
]);
/*
* Configure the list widget
*/
if ($this->showSetup) {
$this->recordsPerPage = $this->getUserPreference('per_page', $this->recordsPerPage);
}
if ($this->showPagination == 'auto') {
$this->showPagination = $this->recordsPerPage && $this->recordsPerPage > 0;
}
if ($this->customViewPath) {
$this->addViewPath($this->customViewPath);
}
$this->validateModel();
$this->validateTree();
}
/**
* @inheritDoc
*/
protected function loadAssets()
{
$this->addJs('js/winter.list.js', 'core');
}
/**
* Renders the widget.
*/
public function render()
{
$this->prepareVars();
return $this->makePartial('list-container');
}
/**
* Prepares the list data
*/
public function prepareVars()
{
$this->vars['cssClasses'] = implode(' ', $this->cssClasses);
$this->vars['columns'] = $this->getVisibleColumns();
$this->vars['columnTotal'] = $this->getTotalColumns();
$this->vars['records'] = $this->getRecords();
$this->vars['noRecordsMessage'] = trans($this->noRecordsMessage);
$this->vars['showCheckboxes'] = $this->showCheckboxes;
$this->vars['showSetup'] = $this->showSetup;
$this->vars['showPagination'] = $this->showPagination;
$this->vars['showPageNumbers'] = $this->showPageNumbers;
$this->vars['showSorting'] = $this->showSorting;
$this->vars['sortColumn'] = $this->getSortColumn();
$this->vars['sortDirection'] = $this->sortDirection;
$this->vars['showTree'] = $this->showTree;
$this->vars['treeLevel'] = 0;
if ($this->showPagination) {
$this->vars['pageCurrent'] = $this->records->currentPage();
// Store the currently visited page number in the session so the same
// data can be displayed when the user returns to this list.
$this->putSession('lastVisitedPage', $this->vars['pageCurrent']);
if ($this->showPageNumbers) {
$this->vars['recordTotal'] = $this->records->total();
$this->vars['pageLast'] = $this->records->lastPage();
$this->vars['pageFrom'] = $this->records->firstItem();
$this->vars['pageTo'] = $this->records->lastItem();
}
else {
$this->vars['hasMorePages'] = $this->records->hasMorePages();
}
}
else {
$this->vars['recordTotal'] = $this->records->count();
$this->vars['pageCurrent'] = 1;
}
}
/**
* Event handler for refreshing the list.
*/
public function onRefresh()
{
$this->prepareVars();
return ['#'.$this->getId() => $this->makePartial('list')];
}
/**
* Event handler for switching the page number.
*/
public function onPaginate()
{
$this->currentPageNumber = post('page');
return $this->onRefresh();
}
/**
* Event handler for changing the filter
*/
public function onFilter()
{
$this->currentPageNumber = 1;
return $this->onRefresh();
}
/**
* Validate the supplied form model.
* @return void
*/
protected function validateModel()
{
if (!$this->model) {
throw new ApplicationException(Lang::get(
'backend::lang.list.missing_model',
['class'=>get_class($this->controller)]
));
}
if (!$this->model instanceof Model) {
throw new ApplicationException(Lang::get(
'backend::lang.model.invalid_class',
['model'=>get_class($this->model), 'class'=>get_class($this->controller)]
));
}
return $this->model;
}
/**
* Replaces the @ symbol with a table name in a model
* @param string $sql
* @param string $table
* @return string
*/
protected function parseTableName($sql, $table)
{
return str_replace('@', $table.'.', $sql);
}
/**
* Applies any filters to the model.
*/
public function prepareQuery()
{
$query = $this->model->newQuery();
$primaryTable = $this->model->getTable();
$selects = [$primaryTable.'.*'];
$joins = [];
$withs = [];
$bindings = [];
/**
* @event backend.list.extendQueryBefore
* Provides an opportunity to modify the `$query` object before the List widget applies its scopes to it.
*
* Example usage:
*
* Event::listen('backend.list.extendQueryBefore', function ($listWidget, $query) {
* $query->whereNull('deleted_at');
* });
*
* Or
*
* $listWidget->bindEvent('list.extendQueryBefore', function ($query) {
* $query->whereNull('deleted_at');
* });
*
*/
$this->fireSystemEvent('backend.list.extendQueryBefore', [$query]);
/*
* Prepare searchable column names
*/
$primarySearchable = [];
$relationSearchable = [];
$columnsToSearch = [];
if (
strlen($this->searchTerm) !== 0
&& trim($this->searchTerm) !== ''
&& ($searchableColumns = $this->getSearchableColumns())
) {
foreach ($searchableColumns as $column) {
/*
* Related
*/
if ($this->isColumnRelated($column)) {
$table = $this->model->makeRelation($column->relation)->getTable();
$columnName = isset($column->sqlSelect)
? DbDongle::raw($this->parseTableName($column->sqlSelect, $table))
: $table . '.' . $column->valueFrom;
$relationSearchable[$column->relation][] = $columnName;
}
/*
* Primary
*/
else {
$columnName = isset($column->sqlSelect)
? DbDongle::raw($this->parseTableName($column->sqlSelect, $primaryTable))
: DbDongle::cast(Db::getTablePrefix() . $primaryTable . '.' . $column->columnName, 'TEXT');
$primarySearchable[] = $columnName;
}
}
}
/*
* Prepare related eager loads (withs) and custom selects (joins)
*/
foreach ($this->getVisibleColumns() as $column) {
// If useRelationCount is enabled, eager load the count of the relation into $relation_count
if ($column->relation && ($column->config['useRelationCount'] ?? false)) {
$query->withCount($column->relation);
}
if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom))) {
continue;
}
if (isset($column->valueFrom)) {
$withs[] = $column->relation;
}
$joins[] = $column->relation;
}
/*
* Add eager loads to the query
*/
if ($withs) {
$query->with(array_unique($withs));
}
/*
* Apply search term
*/
$query->where(function ($innerQuery) use ($primarySearchable, $relationSearchable, $joins) {
/*
* Search primary columns
*/
if (count($primarySearchable) > 0) {
$this->applySearchToQuery($innerQuery, $primarySearchable, 'or');
}
/*
* Search relation columns
*/
if ($joins) {
foreach (array_unique($joins) as $join) {
/*
* Apply a supplied search term for relation columns and
* constrain the query only if there is something to search for
*/
$columnsToSearch = array_get($relationSearchable, $join, []);
if (count($columnsToSearch) > 0) {
$innerQuery->orWhereHas($join, function ($_query) use ($columnsToSearch) {
$this->applySearchToQuery($_query, $columnsToSearch);
});
}
}
}
});
/*
* Custom select queries
*/
foreach ($this->getVisibleColumns() as $column) {
if (!isset($column->sqlSelect)) {
continue;
}
$alias = $query->getQuery()->getGrammar()->wrap($column->columnName);
/*
* Relation column
*/
if (isset($column->relation)) {
// @todo Find a way...
$relationType = $this->model->getRelationType($column->relation);
if ($relationType == 'morphTo') {
throw new ApplicationException('The relationship morphTo is not supported for list columns.');
}
$table = $this->model->makeRelation($column->relation)->getTable();
$sqlSelect = $this->parseTableName($column->sqlSelect, $table);
/*
* Manipulate a count query for the sub query
*/
$relationObj = $this->model->{$column->relation}();
$countQuery = $relationObj->getRelationExistenceQuery($relationObj->getRelated()->newQueryWithoutScopes(), $query);
$joinSql = $this->isColumnRelated($column, true)
? DbDongle::raw("group_concat(" . $sqlSelect . " separator ', ')")
: DbDongle::raw($sqlSelect);
$joinQuery = $countQuery->select($joinSql);
if (!empty($column->config['conditions'])) {
$joinQuery->whereRaw(DbDongle::parse($column->config['conditions']));
}
$joinSql = $joinQuery->toSql();
$selects[] = Db::raw("(".$joinSql.") as ".$alias);
/*
* If this is a polymorphic relation there will be bindings that need to be added to the query
*/
$bindings = array_merge($bindings, $countQuery->getBindings());
}
/*
* Primary column
*/
else {
$sqlSelect = $this->parseTableName($column->sqlSelect, $primaryTable);
$selects[] = DbDongle::raw($sqlSelect . ' as '. $alias);
}
}
/*
* Apply sorting
*/
if (($sortColumn = $this->getSortColumn()) && !$this->showTree) {
if (($column = array_get($this->allColumns, $sortColumn)) && $column->valueFrom) {
$sortColumn = $this->isColumnPivot($column)
? 'pivot_' . $column->valueFrom
: $column->valueFrom;
}
// Set the sorting column to $relation_count if useRelationCount enabled
if (isset($column->relation) && ($column->config['useRelationCount'] ?? false)) {
$sortColumn = Str::snake($column->relation) . '_count';
}
$query->orderBy($sortColumn, $this->sortDirection);
}
/*
* Apply filters
*/
foreach ($this->filterCallbacks as $callback) {
$callback($query);
}
/*
* Add custom selects
*/
$query->addSelect($selects);
/*
* Add bindings for polymorphic relations
*/
$query->addBinding($bindings, 'select');
/**
* @event backend.list.extendQuery
* Provides an opportunity to modify and / or return the `$query` object after the List widget has applied its scopes to it and before it's used to get the records.
*
* Example usage:
*
* Event::listen('backend.list.extendQuery', function ($listWidget, $query) {
* $newQuery = MyModel::newQuery();
* return $newQuery;
* });
*
* Or
*
* $listWidget->bindEvent('list.extendQuery', function ($query) {
* $query->whereNull('deleted_at');
* });
*
*/
if ($event = $this->fireSystemEvent('backend.list.extendQuery', [$query])) {
return $event;
}
return $query;
}
public function prepareModel()
{
traceLog('Method ' . __METHOD__ . '() has been deprecated, please use the ' . __CLASS__ . '::prepareQuery() method instead.');
return $this->prepareQuery();
}
/**
* Returns all the records from the supplied model, after filtering.
* @return Collection
*/
protected function getRecords()
{
$query = $this->prepareQuery();
if ($this->showTree) {
$records = $query->getNested();
}
elseif ($this->showPagination) {
$method = $this->showPageNumbers ? 'paginate' : 'simplePaginate';
$currentPageNumber = $this->getCurrentPageNumber($query);
$records = $query->{$method}($this->recordsPerPage, $currentPageNumber);
}
else {
$records = $query->get();
}
/**
* @event backend.list.extendRecords
* Provides an opportunity to modify and / or return the `$records` Collection object before the widget uses it.
*
* Example usage:
*
* Event::listen('backend.list.extendRecords', function ($listWidget, $records) {
* $model = MyModel::where('always_include', true)->first();
* $records->prepend($model);
* });
*
* Or
*
* $listWidget->bindEvent('list.extendRecords', function ($records) {
* $model = MyModel::where('always_include', true)->first();
* $records->prepend($model);
* });
*
*/
if ($event = $this->fireSystemEvent('backend.list.extendRecords', [&$records])) {
$records = $event;
}
return $this->records = $records;
}
/**
* Returns the current page number for the list.
*
* This will override the current page number provided by the user if it is past the last page of available records.
*
* @param object $query
* @return int
*/
protected function getCurrentPageNumber($query)
{
$currentPageNumber = $this->currentPageNumber;
if (empty($currentPageNumber)) {
$currentPageNumber = $this->getSession('lastVisitedPage');
}
$currentPageNumber = intval($currentPageNumber);
if ($currentPageNumber > 1) {
$count = $query->count();
// If the current page number is higher than the amount of available pages, go to the last available page
if ($count <= (($currentPageNumber - 1) * $this->recordsPerPage)) {
$currentPageNumber = ceil($count / $this->recordsPerPage);
}
}
return $currentPageNumber;
}
/**
* Returns the record URL address for a list row.
* @param Model $record
* @return string
*/
public function getRecordUrl($record)
{
if (isset($this->recordOnClick)) {
return 'javascript:;';
}
if (!isset($this->recordUrl)) {
return null;
}
$url = RouterHelper::replaceParameters($record, $this->recordUrl);
return Backend::url($url);
}
/**
* Returns the onclick event for a list row.
* @param Model $record
* @return string
*/
public function getRecordOnClick($record)
{
if (!isset($this->recordOnClick)) {
return null;
}
$recordOnClick = RouterHelper::replaceParameters($record, $this->recordOnClick);
return Html::attributes(['onclick' => $recordOnClick]);
}
/**
* Get all the registered columns for the instance.
* @return array
*/
public function getColumns()
{
return $this->allColumns ?: $this->defineListColumns();
}
/**
* Get a specified column object
* @param string $column
* @return mixed
*/
public function getColumn($column)
{
if (!isset($this->allColumns[$column])) {
throw new ApplicationException('No definition for column ' . $column);
}
return $this->allColumns[$column];
}
/**
* Returns the list columns that are visible by list settings or default
*/
public function getVisibleColumns()
{
$definitions = $this->defineListColumns();
$columns = [];
/*
* Supplied column list
*/
if ($this->showSetup && $this->columnOverride === null) {
$this->columnOverride = $this->getUserPreference('visible', null);
}
if ($this->columnOverride && is_array($this->columnOverride)) {
$invalidColumns = array_diff($this->columnOverride, array_keys($definitions));
if (!count($definitions)) {
throw new ApplicationException(Lang::get(
'backend::lang.list.missing_column',
['columns'=>implode(',', $invalidColumns)]
));
}
$availableColumns = array_intersect($this->columnOverride, array_keys($definitions));
foreach ($availableColumns as $columnName) {
$definitions[$columnName]->invisible = false;
$columns[$columnName] = $definitions[$columnName];
}
}
/*
* Use default column list
*/
else {
foreach ($definitions as $columnName => $column) {
if ($column->invisible) {
continue;
}
$columns[$columnName] = $definitions[$columnName];
}
}
return $this->visibleColumns = $columns;
}
/**
* Builds an array of list columns with keys as the column name and values as a ListColumn object.
*/
protected function defineListColumns()
{
if (!isset($this->columns) || !is_array($this->columns) || !count($this->columns)) {
$class = get_class($this->model instanceof Model ? $this->model : $this->controller);
throw new ApplicationException(Lang::get('backend::lang.list.missing_columns', compact('class')));
}
$this->addColumns($this->columns);
/**
* @event backend.list.extendColumns
* Provides an opportunity to modify the columns of a List widget
*
* Example usage:
*
* Event::listen('backend.list.extendColumns', function ($listWidget) {
* // Only for the User controller
* if (!$listWidget->getController() instanceof \Backend\Controllers\Users) {
* return;
* }
*
* // Only for the User model
* if (!$listWidget->model instanceof \Backend\Models\User) {
* return;
* }
*
* // Add an extra birthday column
* $listWidget->addColumns([
* 'birthday' => [
* 'label' => 'Birthday'
* ]
* ]);
*
* // Remove a Surname column
* $listWidget->removeColumn('surname');
* });
*
* Or
*
* $listWidget->bindEvent('list.extendColumns', function () use ($listWidget) {
* // Only for the User controller
* if (!$listWidget->getController() instanceof \Backend\Controllers\Users) {
* return;
* }
*
* // Only for the User model
* if (!$listWidget->model instanceof \Backend\Models\User) {
* return;
* }
*
* // Add an extra birthday column
* $listWidget->addColumns([
* 'birthday' => [
* 'label' => 'Birthday'
* ]
* ]);
*
* // Remove a Surname column
* $listWidget->removeColumn('surname');
* });
*
*/
$this->fireSystemEvent('backend.list.extendColumns');
/*
* Use a supplied column order
*/
if ($columnOrder = $this->getUserPreference('order', null)) {
$orderedDefinitions = [];
foreach ($columnOrder as $column) {
if (isset($this->allColumns[$column])) {
$orderedDefinitions[$column] = $this->allColumns[$column];
}
}
$this->allColumns = array_merge($orderedDefinitions, $this->allColumns);
}
return $this->allColumns;
}
/**
* Programatically add columns, used internally and for extensibility.
* @param array $columns Column definitions
*/
public function addColumns(array $columns)
{
/*
* Build a final collection of list column objects
*/
foreach ($columns as $columnName => $config) {
// Check if user has permissions to show this column
$permissions = array_get($config, 'permissions');
if (!empty($permissions) && !BackendAuth::getUser()->hasAccess($permissions, false)) {
continue;
}
$this->allColumns[$columnName] = $this->makeListColumn($columnName, $config);
}
}
/**
* Programatically remove a column, used for extensibility.
* @param string $column Column name
*/
public function removeColumn($columnName)
{
if (isset($this->allColumns[$columnName])) {
unset($this->allColumns[$columnName]);
}
}
/**
* Creates a list column object from it's name and configuration.
*/
protected function makeListColumn($name, $config)
{
if (is_string($config)) {
$label = $config;
}
elseif (isset($config['label'])) {
$label = $config['label'];
}
else {
$label = studly_case($name);
}
/*
* Auto configure pivot relation
*/
if (starts_with($name, 'pivot[') && strpos($name, ']') !== false) {
$_name = HtmlHelper::nameToArray($name);
$relationName = array_shift($_name);
$valueFrom = array_shift($_name);
if (count($_name) > 0) {
$valueFrom .= '['.implode('][', $_name).']';
}
$config['relation'] = $relationName;
$config['valueFrom'] = $valueFrom;
$config['searchable'] = false;
}
/*
* Auto configure standard relation
*/
elseif (strpos($name, '[') !== false && strpos($name, ']') !== false) {
$config['valueFrom'] = $name;
$config['sortable'] = false;
$config['searchable'] = false;
}
$columnType = $config['type'] ?? null;
$column = new ListColumn($name, $label);
$column->displayAs($columnType, $config);
return $column;
}
/**
* Calculates the total columns used in the list, including checkboxes
* and other additions.
*/
protected function getTotalColumns()
{
$columns = $this->visibleColumns ?: $this->getVisibleColumns();
$total = count($columns);
if ($this->showCheckboxes) {
$total++;
}
if ($this->showSetup) {
$total++;
}
if ($this->showTree) {
$total++;
}
return $total;
}
/**
* Looks up the column header
*/
public function getHeaderValue($column)
{
$value = Lang::get($column->label);
/**
* @event backend.list.overrideHeaderValue
* Overrides the column header value in a list widget.
*
* If a value is returned from this event, it will be used as the value for the provided column.
* `$value` is passed by reference so modifying the variable in place is also supported. Example usage:
*
* Event::listen('backend.list.overrideHeaderValue', function ($listWidget, $column, &$value) {
* $value .= '-modified';
* });
*
* Or
*
* $listWidget->bindEvent('list.overrideHeaderValue', function ($column, $value) {
* return 'Custom header value';
* });
*
*/
if ($response = $this->fireSystemEvent('backend.list.overrideHeaderValue', [$column, &$value])) {
$value = $response;
}