-
Notifications
You must be signed in to change notification settings - Fork 619
/
Matrix.php
1551 lines (1345 loc) · 50.2 KB
/
Matrix.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
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\fields;
use Craft;
use craft\base\EagerLoadingFieldInterface;
use craft\base\Element;
use craft\base\ElementContainerFieldInterface;
use craft\base\ElementInterface;
use craft\base\Field;
use craft\base\GqlInlineFragmentFieldInterface;
use craft\base\GqlInlineFragmentInterface;
use craft\base\NestedElementInterface;
use craft\behaviors\EventBehavior;
use craft\db\Query;
use craft\db\Table as DbTable;
use craft\elements\db\ElementQuery;
use craft\elements\db\ElementQueryInterface;
use craft\elements\db\EntryQuery;
use craft\elements\ElementCollection;
use craft\elements\Entry;
use craft\elements\NestedElementManager;
use craft\elements\User;
use craft\enums\ElementIndexViewMode;
use craft\enums\PropagationMethod;
use craft\errors\InvalidFieldException;
use craft\events\BulkElementsEvent;
use craft\events\CancelableEvent;
use craft\events\DefineEntryTypesForFieldEvent;
use craft\fields\conditions\EmptyFieldConditionRule;
use craft\gql\arguments\elements\Entry as EntryArguments;
use craft\gql\resolvers\elements\Entry as EntryResolver;
use craft\gql\types\generators\EntryType as EntryTypeGenerator;
use craft\gql\types\input\Matrix as MatrixInputType;
use craft\helpers\ArrayHelper;
use craft\helpers\Gql;
use craft\helpers\Html;
use craft\helpers\Json;
use craft\helpers\Queue;
use craft\helpers\StringHelper;
use craft\i18n\Translation;
use craft\models\EntryType;
use craft\queue\jobs\ApplyNewPropagationMethod;
use craft\queue\jobs\ResaveElements;
use craft\validators\ArrayValidator;
use craft\validators\StringValidator;
use craft\validators\UriFormatValidator;
use craft\web\assets\matrix\MatrixAsset;
use craft\web\View;
use GraphQL\Type\Definition\Type;
use Illuminate\Support\Collection;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\db\Expression;
/**
* Matrix field type
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class Matrix extends Field implements
ElementContainerFieldInterface,
EagerLoadingFieldInterface,
GqlInlineFragmentFieldInterface
{
/**
* @event DefineEntryTypesForFieldEvent The event that is triggered when defining the available entry types.
* @since 5.0.0
*/
public const EVENT_DEFINE_ENTRY_TYPES = 'defineEntryTypes';
/** @since 5.0.0 */
public const VIEW_MODE_CARDS = 'cards';
/** @since 5.0.0 */
public const VIEW_MODE_BLOCKS = 'blocks';
/** @since 5.0.0 */
public const VIEW_MODE_INDEX = 'index';
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('app', 'Matrix');
}
/**
* @inheritdoc
*/
public static function icon(): string
{
return 'binary';
}
/**
* @inheritdoc
*/
public static function supportedTranslationMethods(): array
{
// Don't ever automatically propagate values to other sites.
return [
self::TRANSLATION_METHOD_SITE,
];
}
/**
* @inheritdoc
*/
public static function phpType(): string
{
return sprintf('\\%s|\\%s<\\%s>', EntryQuery::class, ElementCollection::class, Entry::class);
}
/**
* @inheritdoc
*/
public static function dbType(): array|string|null
{
return null;
}
/**
* @inheritdoc
*/
public static function queryCondition(array $instances, mixed $value, array &$params): array
{
/** @var self $field */
$field = reset($instances);
$ns = $field->handle . '_' . StringHelper::randomString(5);
$existsQuery = (new Query())
->from(["entries_$ns" => DbTable::ENTRIES])
->innerJoin(["elements_$ns" => DbTable::ELEMENTS], "[[elements_$ns.id]] = [[entries_$ns.id]]")
->innerJoin(["elements_owners_$ns" => DbTable::ELEMENTS_OWNERS], "[[elements_owners_$ns.elementId]] = [[elements_$ns.id]]")
->andWhere([
"entries_$ns.fieldId" => $field->id,
"elements_$ns.enabled" => true,
"elements_$ns.dateDeleted" => null,
"[[elements_owners_$ns.ownerId]]" => new Expression('[[elements.id]]'),
]);
if ($value === 'not :empty:') {
$value = ':notempty:';
}
if ($value === ':empty:') {
return ['not exists', $existsQuery];
}
if ($value !== ':notempty:') {
$ids = $value;
if (!is_array($ids)) {
$ids = is_string($ids) ? StringHelper::split($ids) : [$ids];
}
$ids = array_map(function($id) {
return $id instanceof Entry ? $id->id : (int)$id;
}, $ids);
$existsQuery->andWhere(["entries_$ns.id" => $ids]);
}
return ['exists', $existsQuery];
}
/**
* Returns the “Default Table Columns” options for the given entry types.
*
* @param EntryType[] $entryTypes
* @return array
* @since 5.0.0
*/
public static function defaultTableColumnOptions(array $entryTypes): array
{
$fieldLayouts = array_map(fn(EntryType $entryType) => $entryType->getFieldLayout(), $entryTypes);
$elementSources = Craft::$app->getElementSources();
$tableColumns = array_merge(
$elementSources->getAvailableTableAttributes(Entry::class),
$elementSources->getTableAttributesForFieldLayouts($fieldLayouts),
);
$options = [];
foreach ($tableColumns as $attribute => $column) {
$options[] = ['label' => $column['label'], 'value' => $attribute];
}
return $options;
}
/**
* @var int|null Min entries
* @since 5.0.0
*/
public ?int $minEntries = null;
/**
* @var int|null Max entries
* @since 5.0.0
*/
public ?int $maxEntries = null;
/**
* @var string The view mode
* @phpstan-var self::VIEW_MODE_*
* @since 5.0.0
*/
public string $viewMode = self::VIEW_MODE_CARDS;
/**
* @var bool Whether cards should be shown in a multi-column grid
* @since 5.0.0
*/
public bool $showCardsInGrid = false;
/**
* @var bool Include table view in element indexes
* @since 5.0.0
*/
public bool $includeTableView = false;
/**
* @var string[] The default table columns to show in table view
* @since 5.0.0
*/
public array $defaultTableColumns = [];
/**
* @var int|null The total entries to display per page within element indexes
* @since 5.0.0
*/
public ?int $pageSize = null;
/**
* @var string|null The “New entry” button label.
* @since 5.0.0
*/
public ?string $createButtonLabel = null;
/**
* @var PropagationMethod Propagation method
*
* This will be set to one of the following:
*
* - [[PropagationMethod::None]] – Only save entries in the site they were created in
* - [[PropagationMethod::SiteGroup]] – Save entries to other sites in the same site group
* - [[PropagationMethod::Language]] – Save entries to other sites with the same language
* - [[PropagationMethod::Custom]] – Save entries to other sites based on a custom [[$propagationKeyFormat|propagation key format]]
* - [[PropagationMethod::All]] – Save entries to all sites supported by the owner element
*
* @since 3.2.0
*/
public PropagationMethod $propagationMethod = PropagationMethod::All;
/**
* @var string|null The field’s propagation key format, if [[propagationMethod]] is `custom`
* @since 3.7.0
*/
public ?string $propagationKeyFormat = null;
/**
* @var array{uriFormat:string|null,template?:string|null,errors?:array}[] Site settings
* @since 5.0.0
*/
public array $siteSettings = [];
/**
* @var EntryType[] The field’s available entry types
* @see getEntryTypes()
* @see setEntryTypes()
*/
private array $_entryTypes = [];
/**
* @see entryManager()
*/
private NestedElementManager $_entryManager;
/**
* @inheritdoc
*/
public function __construct($config = [])
{
// Config normalization
unset($config['contentTable']);
if (array_key_exists('localizeBlocks', $config)) {
$config['propagationMethod'] = $config['localizeBlocks'] ? 'none' : 'all';
unset($config['localizeBlocks']);
}
if (isset($config['entryTypes']) && $config['entryTypes'] === '') {
$config['entryTypes'] = [];
}
if (array_key_exists('minBlocks', $config)) {
$config['minEntries'] = ArrayHelper::remove($config, 'minBlocks');
}
if (array_key_exists('maxBlocks', $config)) {
$config['maxEntries'] = ArrayHelper::remove($config, 'maxBlocks');
}
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function init(): void
{
parent::init();
foreach ($this->siteSettings as &$siteSettings) {
if (($siteSettings['uriFormat'] ?? null) === '') {
unset($siteSettings['uriFormat']);
}
if (($siteSettings['template'] ?? null) === '') {
unset($siteSettings['template']);
}
}
if ($this->viewMode === self::VIEW_MODE_BLOCKS) {
$this->includeTableView = false;
$this->pageSize = null;
}
if (!$this->includeTableView) {
$this->defaultTableColumns = [];
}
if ($this->minEntries === 0) {
$this->minEntries = null;
}
if ($this->maxEntries === 0) {
$this->maxEntries = null;
}
}
/**
* @inheritdoc
*/
public function settingsAttributes(): array
{
return ArrayHelper::withoutValue(parent::settingsAttributes(), 'localizeEntries');
}
/**
* @inheritdoc
*/
public function getSettings(): array
{
$settings = parent::getSettings();
$settings['entryTypes'] = array_map(fn(EntryType $entryType) => $entryType->uid, $this->_entryTypes);
return $settings;
}
/**
* @inheritdoc
*/
protected function defineRules(): array
{
$rules = parent::defineRules();
$rules[] = [['entryTypes'], ArrayValidator::class, 'min' => 1, 'skipOnEmpty' => false];
$rules[] = [['siteSettings'], fn() => $this->validateSiteSettings()];
$rules[] = [['minEntries', 'maxEntries'], 'integer', 'min' => 0];
$rules[] = [['viewMode'], 'in', 'range' => [
self::VIEW_MODE_CARDS,
self::VIEW_MODE_INDEX,
self::VIEW_MODE_BLOCKS,
]];
return $rules;
}
private function validateSiteSettings(): void
{
foreach ($this->siteSettings as $uid => &$siteSettings) {
unset($siteSettings['errors']);
if (isset($siteSettings['uriFormat'])) {
// Remove any leading or trailing slashes/spaces
$siteSettings['uriFormat'] = trim($siteSettings['uriFormat'], '/ ');
if (!(new UriFormatValidator())->validate($siteSettings['uriFormat'], $error)) {
$error = str_replace(Craft::t('yii', 'the input value'), Craft::t('app', 'Entry URI Format'), $error);
$siteSettings['errors']['uriFormat'][] = $error;
$this->addError("siteSettings[$uid].uriFormat", $error);
}
}
if (isset($siteSettings['template'])) {
if (!(new StringValidator(['max' => 500]))->validate($siteSettings['template'], $error)) {
$error = str_replace(Craft::t('yii', 'the input value'), Craft::t('app', 'Template'), $error);
$siteSettings['errors']['template'][] = $error;
$this->addError("siteSettings[$uid].template", $error);
}
}
}
}
private function entryManager(): NestedElementManager
{
if (!isset($this->_entryManager)) {
$this->_entryManager = new NestedElementManager(
Entry::class,
fn(ElementInterface $owner) => $this->createEntryQuery($owner),
[
'field' => $this,
'criteria' => [
'fieldId' => $this->id,
],
'propagationMethod' => $this->propagationMethod,
'propagationKeyFormat' => $this->propagationKeyFormat,
],
);
$this->_entryManager->on(NestedElementManager::EVENT_AFTER_SAVE_ELEMENTS, [$this, 'afterSaveEntries']);
}
return $this->_entryManager;
}
/**
* Returns the available entry types.
*
* @return EntryType[]
*/
public function getEntryTypes(): array
{
return $this->_entryTypes;
}
/**
* Returns the available entry types for the given owner element.
*
* @param Entry[] $value
* @param ElementInterface|null $element
* @return EntryType[]
* @since 5.0.0
*/
public function getEntryTypesForField(array $value, ?ElementInterface $element): array
{
// Let plugins/modules override which entry types should be available for this field
$event = new DefineEntryTypesForFieldEvent([
'entryTypes' => $this->getEntryTypes(),
'element' => $element,
'value' => $value,
]);
$this->trigger(self::EVENT_DEFINE_ENTRY_TYPES, $event);
$entryTypes = array_values($event->entryTypes);
if (empty($entryTypes)) {
throw new InvalidConfigException('At least one entry type is required.');
}
return $entryTypes;
}
/**
* Sets the available entry types.
*
* @param array<int|string|EntryType> $entryTypes The entry types, or their IDs or UUIDs
*/
public function setEntryTypes(array $entryTypes): void
{
$entriesService = Craft::$app->getEntries();
$this->_entryTypes = array_values(array_filter(array_map(function(EntryType|string|int $entryType) use ($entriesService) {
if (is_numeric($entryType)) {
$entryType = $entriesService->getEntryTypeById($entryType);
} elseif (is_string($entryType)) {
$entryTypeUid = $entryType;
$entryType = $entriesService->getEntryTypeByUid($entryTypeUid);
} elseif (!$entryType instanceof EntryType) {
throw new InvalidArgumentException('Invalid entry type');
}
return $entryType;
}, $entryTypes)));
}
/**
* @inheritdoc
*/
public function getFieldLayoutProviders(): array
{
return $this->getEntryTypes();
}
/**
* @inheritdoc
*/
public function getUriFormatForElement(NestedElementInterface $element): ?string
{
$site = $element->getSite();
return $this->siteSettings[$site->uid]['uriFormat'] ?? null;
}
/**
* @inheritdoc
*/
public function getRouteForElement(NestedElementInterface $element): mixed
{
$site = $element->getSite();
return [
'templates/render', [
'template' => $this->siteSettings[$site->uid]['template'] ?? '',
'variables' => [
'entry' => $element,
],
],
];
}
/**
* @inheritdoc
*/
public function getSupportedSitesForElement(NestedElementInterface $element): array
{
try {
$owner = $element->getOwner();
} catch (InvalidConfigException) {
$owner = $element->duplicateOf;
}
if (!$owner) {
return [Craft::$app->getSites()->getPrimarySite()->id];
}
return $this->entryManager()->getSupportedSiteIds($owner);
}
/**
* @inheritdoc
*/
public function canViewElement(NestedElementInterface $element, User $user): ?bool
{
$owner = $element->getOwner();
return $owner && Craft::$app->getElements()->canView($owner, $user);
}
/**
* @inheritdoc
*/
public function canSaveElement(NestedElementInterface $element, User $user): ?bool
{
$owner = $element->getOwner();
if (!$owner || !Craft::$app->getElements()->canSave($owner, $user)) {
return false;
}
// If this is a new entry, make sure we aren't hitting the Max Entries limit
if (!$element->id && $element->getIsCanonical() && $this->maxEntriesReached($element->getOwner())) {
return false;
}
return true;
}
/**
* @inheritdoc
*/
public function canDuplicateElement(NestedElementInterface $element, User $user): ?bool
{
$owner = $element->getOwner();
if (!$owner || !Craft::$app->getElements()->canSave($owner, $user)) {
return false;
}
// Make sure we aren't hitting the Max Entries limit
return !$this->maxEntriesReached($owner);
}
/**
* @inheritdoc
*/
public function canDeleteElement(NestedElementInterface $element, User $user): ?bool
{
$owner = $element->getOwner();
if (!$owner || !Craft::$app->getElements()->canSave($element->getOwner(), $user)) {
return false;
}
// Make sure we aren't hitting the Min Entries limit
return !$this->minEntriesReached($owner);
}
/**
* @inheritdoc
*/
public function canDeleteElementForSite(NestedElementInterface $element, User $user): ?bool
{
$owner = $element->getOwner();
if (!$owner || !Craft::$app->getElements()->canSave($owner, $user)) {
return false;
}
// Make sure we aren't hitting the Min Entries limit
return !$this->minEntriesReached($owner);
}
private function minEntriesReached(ElementInterface $owner): bool
{
return (
$this->minEntries &&
$this->minEntries >= $this->totalEntries($owner)
);
}
private function maxEntriesReached(ElementInterface $owner): bool
{
return (
$this->maxEntries &&
$this->maxEntries <= $this->totalEntries($owner)
);
}
private function totalEntries(ElementInterface $owner): int
{
/** @var EntryQuery|ElementCollection $value */
$value = $owner->getFieldValue($this->handle);
if ($value instanceof EntryQuery) {
return (clone $value)
->status(null)
->siteId($owner->siteId)
->limit(null)
->count();
}
return $value->count();
}
/**
* @inheritdoc
*/
public function getSettingsHtml(): ?string
{
return Craft::$app->getView()->renderTemplate('_components/fieldtypes/Matrix/settings.twig', [
'field' => $this,
'defaultTableColumnOptions' => static::defaultTableColumnOptions($this->getEntryTypes()),
'defaultCreateButtonLabel' => $this->defaultCreateButtonLabel(),
]);
}
/**
* @inheritdoc
*/
public function normalizeValue(mixed $value, ?ElementInterface $element): mixed
{
return $this->_normalizeValueInternal($value, $element, false);
}
/**
* @inheritdoc
*/
public function normalizeValueFromRequest(mixed $value, ?ElementInterface $element): mixed
{
return $this->_normalizeValueInternal($value, $element, true);
}
private function _normalizeValueInternal(mixed $value, ?ElementInterface $element, bool $fromRequest): mixed
{
if ($value instanceof ElementQueryInterface) {
return $value;
}
$query = $this->createEntryQuery($element);
// Set the initially matched elements if $value is already set, which is the case if there was a validation
// error or we're loading an entry revision.
if ($value === '') {
$query->setCachedResult([]);
} elseif ($element && is_array($value)) {
$query->setCachedResult($this->_createEntriesFromSerializedData($value, $element, $fromRequest));
}
return $query;
}
private function createEntryQuery(?ElementInterface $owner): EntryQuery
{
$query = Entry::find();
// Existing element?
if ($owner && $owner->id) {
$query->attachBehavior(self::class, new EventBehavior([
ElementQuery::EVENT_BEFORE_PREPARE => function(
CancelableEvent $event,
EntryQuery $query,
) use ($owner) {
$query->ownerId = $owner->id;
// Clear out id=false if this query was populated previously
if ($query->id === false) {
$query->id = null;
}
// If the owner is a revision, allow revision entries to be returned as well
if ($owner->getIsRevision()) {
$query
->revisions(null)
->trashed(null);
}
},
], true));
// Prepare the query for lazy eager loading
$query->prepForEagerLoading($this->handle, $owner);
} else {
$query->id = false;
}
$query
->fieldId($this->id)
->siteId($owner->siteId ?? null);
return $query;
}
/**
* @inheritdoc
*/
public function serializeValue(mixed $value, ?ElementInterface $element): mixed
{
/** @var EntryQuery|ElementCollection $value */
$serialized = [];
$new = 0;
foreach ($value->all() as $entry) {
/** @var Entry $entry */
$entryId = $entry->id ?? 'new' . ++$new;
$serialized[$entryId] = [
'title' => $entry->title,
'slug' => $entry->slug,
'type' => $entry->getType()->handle,
'enabled' => $entry->enabled,
'collapsed' => $entry->collapsed,
'fields' => $entry->getSerializedFieldValues(),
];
}
return $serialized;
}
/**
* @inheritdoc
*/
public function copyValue(ElementInterface $from, ElementInterface $to): void
{
// We'll do it later from afterElementPropagate()
}
/**
* @inheritdoc
*/
public function getElementConditionRuleType(): array|string|null
{
return EmptyFieldConditionRule::class;
}
/**
* @inheritdoc
*/
public function getIsTranslatable(?ElementInterface $element): bool
{
return $this->entryManager()->getIsTranslatable($element);
}
/**
* @inheritdoc
*/
public function getTranslationDescription(?ElementInterface $element): ?string
{
return $this->entryManager()->getTranslationDescription($element);
}
/**
* @inheritdoc
* @throws InvalidConfigException
*/
protected function inputHtml(mixed $value, ?ElementInterface $element, bool $inline): string
{
return match ($this->viewMode) {
self::VIEW_MODE_BLOCKS => $this->blockInputHtml($value, $element),
default => $this->nestedElementManagerHtml($element),
};
}
private function blockInputHtml(EntryQuery|ElementCollection|null $value, ?ElementInterface $element): string
{
if (!$element?->id) {
$message = Craft::t('app', '{nestedType} can only be created after the {ownerType} has been saved.', [
'nestedType' => Entry::pluralDisplayName(),
'ownerType' => $element ? $element::lowerDisplayName() : Craft::t('app', 'element'),
]);
return Html::tag('div', $message, ['class' => 'pane no-border zilch small']);
}
if ($element !== null && $element->hasEagerLoadedElements($this->handle)) {
$value = $element->getEagerLoadedElements($this->handle)->all();
}
if ($value instanceof EntryQuery) {
$value = $value->getCachedResult() ?? $value->limit(null)->status(null)->all();
}
$view = Craft::$app->getView();
$id = $this->getInputId();
/** @var Entry[] $value */
$entryTypes = $this->getEntryTypesForField($value, $element);
// Get the entry types data
$entryTypeInfo = array_map(fn(EntryType $entryType) => [
'id' => $entryType->id,
'handle' => $entryType->handle,
'name' => Craft::t('site', $entryType->name),
], $entryTypes);
$createDefaultEntries = (
$this->minEntries != 0 &&
count($entryTypeInfo) === 1 &&
!$element->hasErrors($this->handle)
);
$staticEntries = (
$createDefaultEntries &&
$this->minEntries == $this->maxEntries &&
$this->maxEntries >= count($value)
);
$view->registerAssetBundle(MatrixAsset::class);
$settings = [
'fieldId' => $this->id,
'maxEntries' => $this->maxEntries,
'namespace' => $view->getNamespace(),
'baseInputName' => $view->namespaceInputName($this->handle),
'ownerElementType' => $element::class,
'ownerId' => $element->id,
'siteId' => $element->siteId,
'staticEntries' => $staticEntries,
];
$js = 'const input = new Craft.MatrixInput(' .
'"' . $view->namespaceInputId($id) . '", ' .
Json::encode($entryTypeInfo) . ', ' .
'"' . $view->namespaceInputName($this->handle) . '", ' .
Json::encode($settings) .
');';
// Safe to create the default entries?
if ($createDefaultEntries && count($value) < $this->minEntries) {
// @link https://github.com/craftcms/cms/issues/12973
// for fields with minEntries set Craft.MatrixInput.addEntry() is called before new Craft.ElementEditor(),
// so when we get our initialSerializedValue() for the ElementEditor,
// the entry is already there which means the field is reported as not changed since the init
// and so not passed to PHP for save
$view->setInitialDeltaValue($this->handle, null);
$js .= "\n" . <<<JS
input.on('afterInit', async () => {
input.elementEditor?.pause();
JS . "\n";
$entryTypeJs = Json::encode($entryTypes[0]->handle);
for ($i = count($value); $i < $this->minEntries; $i++) {
$js .= <<<JS
await input.addEntry($entryTypeJs, null, false);
JS . "\n";
}
$js .= <<<JS
input.elementEditor?.resume();
});
JS;
}
$view->registerJs("(() => {\n$js\n})();");
return $view->renderTemplate('_components/fieldtypes/Matrix/input.twig', [
'id' => $id,
'field' => $this,
'name' => $this->handle,
'entryTypes' => $entryTypes,
'entries' => $value,
'static' => false,
'staticEntries' => $staticEntries,
'createButtonLabel' => $this->createButtonLabel(),
'labelId' => $this->getLabelId(),
]);
}
private function nestedElementManagerHtml(?ElementInterface $owner, bool $static = false): string
{
$entryTypes = $this->getEntryTypes();
$config = [
'showInGrid' => $this->showCardsInGrid,
];
if (!$static) {
$config += [
'sortable' => true,
'canCreate' => true,
'createAttributes' => array_map(fn(EntryType $entryType) => [
'icon' => $entryType->icon,
'color' => $entryType->color,
'label' => Craft::t('site', $entryType->name),
'attributes' => [
'fieldId' => $this->id,
'typeId' => $entryType->id,
],
], $entryTypes),
'createButtonLabel' => $this->createButtonLabel(),
'minElements' => $this->minEntries,
'maxElements' => $this->maxEntries,
];
}
if ($this->viewMode === self::VIEW_MODE_CARDS) {
return $this->entryManager()->getCardsHtml($owner, $config);
}
$config += [
'allowedViewModes' => array_filter([
ElementIndexViewMode::Cards,
$this->includeTableView ? ElementIndexViewMode::Table : null,
]),
'showHeaderColumn' => ArrayHelper::contains($entryTypes, fn(EntryType $entryType) => (
$entryType->hasTitleField ||
$entryType->titleFormat
)),
'pageSize' => $this->pageSize ?? 50,
'storageKey' => sprintf('field:%s', $this->uid),
];
if (!$static) {
$config += [
'fieldLayouts' => array_map(fn(EntryType $entryType) => $entryType->getFieldLayout(), $entryTypes),
'defaultTableColumns' => array_map(fn(string $attribute) => [$attribute], $this->defaultTableColumns),
];
}
return $this->entryManager()->getIndexHtml($owner, $config);
}
private function createButtonLabel(): string
{
if (isset($this->createButtonLabel)) {
return Craft::t('site', $this->createButtonLabel);
}
return $this->defaultCreateButtonLabel();
}
private function defaultCreateButtonLabel(): string
{
return Craft::t('app', 'New {type}', [
'type' => Entry::lowerDisplayName(),
]);
}
/**
* @inheritdoc
*/
public function getElementValidationRules(): array
{
return [
[
fn(ElementInterface $element) => $this->validateEntries($element),
'on' => [Element::SCENARIO_ESSENTIALS, Element::SCENARIO_DEFAULT, Element::SCENARIO_LIVE],
'skipOnEmpty' => false,
],
];
}
/**
* @inheritdoc
*/
public function isValueEmpty(mixed $value, ElementInterface $element): bool
{
/** @var EntryQuery|ElementCollection $value */
return $value->count() === 0;
}
private function validateEntries(ElementInterface $element): void
{
/** @var EntryQuery|ElementCollection $value */
$value = $element->getFieldValue($this->handle);
if ($value instanceof EntryQuery) {
/** @var Entry[] $entries */
$entries = $value->getCachedResult() ?? (clone $value)->status(null)->limit(null)->all();
$allEntriesValidate = true;
$scenario = $element->getScenario();