-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathNestedElementManager.php
More file actions
1433 lines (1272 loc) · 57.6 KB
/
NestedElementManager.php
File metadata and controls
1433 lines (1272 loc) · 57.6 KB
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\elements;
use Closure;
use Craft;
use craft\base\Element;
use craft\base\ElementInterface;
use craft\base\FieldInterface;
use craft\base\NestedElementInterface;
use craft\behaviors\DraftBehavior;
use craft\db\Query;
use craft\db\Table;
use craft\elements\actions\ChangeSortOrder;
use craft\elements\actions\MoveDown;
use craft\elements\actions\MoveUp;
use craft\elements\db\ElementQueryInterface;
use craft\enums\Color;
use craft\enums\PropagationMethod;
use craft\events\BulkElementsEvent;
use craft\events\DuplicateNestedElementsEvent;
use craft\helpers\ArrayHelper;
use craft\helpers\Cp;
use craft\helpers\Db;
use craft\helpers\ElementHelper;
use craft\helpers\Html;
use craft\helpers\StringHelper;
use craft\models\Site;
use Generator;
use Throwable;
use yii\base\Component;
use yii\base\InvalidConfigException;
/**
* Nested Element Manager
*
* This can be used by elements or fields to manage nested elements, such as users → addresses,
* or Matrix fields → nested entries.
*
* If this is for a custom field, [[field]] must be set. Otherwise, [[attribute]] must be set.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 5.0.0
*/
class NestedElementManager extends Component
{
private const VIEW_MODE_CARDS = 'cards';
private const VIEW_MODE_INDEX = 'index';
/**
* @event BulkElementsEvent The event that is triggered after nested elements are resaved.
*/
public const EVENT_AFTER_SAVE_ELEMENTS = 'afterSaveElements';
/**
* @event DuplicateNestedElementsEvent The event that is triggered after nested elements are duplicated.
*/
public const EVENT_AFTER_DUPLICATE_NESTED_ELEMENTS = 'afterDuplicateNestedElements';
/**
* @event DuplicateNestedElementsEvent The event that is triggered after revisions are created for nested elements.
* @see createRevisions()
*/
public const EVENT_AFTER_CREATE_REVISIONS = 'afterCreateRevisions';
/**
* @see getSupportedSiteIds()
*/
private static array $renderedPropagationFormats = [];
/**
* Constructor
*
* @param class-string<NestedElementInterface> $elementType The nested element type.
* @param Closure(ElementInterface $owner): ElementQueryInterface $queryFactory A factory method which returns a
* query for fetching nested elements
* @param array $config name-value pairs that will be used to initialize the object properties.
*/
public function __construct(
private readonly string $elementType,
private readonly Closure $queryFactory,
array $config = [],
) {
parent::__construct($config);
}
/**
* @var string|null The attribute name used to access nested elements.
*/
public ?string $attribute = null;
/**
* @var FieldInterface|null The field associated with this nested element manager.
*/
public ?FieldInterface $field = null;
/**
* @var string The name of the element query param that nested elements use to associate with the owner’s ID
*/
public string $ownerIdParam = 'ownerId';
/**
* @var string The name of the element query param that nested elements use to associate with the primary owner’s ID
*/
public string $primaryOwnerIdParam = 'primaryOwnerId';
/**
* @var array Additional element query params that should be set when fetching nested elements.
*/
public array $criteria = [];
/**
* @var Closure|null Closure that will get the value.
*/
public Closure|null $valueGetter = null;
/**
* @var Closure|null|false Closure that will update the value.
*/
public Closure|null|false $valueSetter = null;
/**
* @var PropagationMethod The propagation method that the nested elements should use.
*
* This can be set to one of the following:
*
* - [[PropagationMethod::None]] – Only save elements in the site they were created in
* - [[PropagationMethod::SiteGroup]] – Save elements to other sites in the same site group
* - [[PropagationMethod::Language]] – Save elements to other sites with the same language
* - [[PropagationMethod::Custom]] – Save elements to other sites based on a custom [[$propagationKeyFormat|propagation key format]]
* - [[PropagationMethod::All]] – Save elements to all sites supported by the owner element
*/
public PropagationMethod $propagationMethod = PropagationMethod::All;
/**
* @var string|null The propagation key format that the nested elements should use,
* if [[$propagationMethod]] is set to [[PropagationMethod::Custom]].
*/
public ?string $propagationKeyFormat = null;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if (!isset($this->attribute) && !isset($this->field)) {
throw new InvalidConfigException('NestedElementManager requires that either `attribute` or `field` is set.');
}
if (isset($this->attribute) && isset($this->field)) {
throw new InvalidConfigException('NestedElementManager requires that either `attribute` or `field` is set, but not both.');
}
}
/**
* Returns whether the field or attribute should be shown as translatable in the UI, for the given owner element.
*
* @param ElementInterface|null $owner
* @return bool
*/
public function getIsTranslatable(?ElementInterface $owner = null): bool
{
if ($this->propagationMethod === PropagationMethod::Custom && $this->propagationKeyFormat !== null) {
return (
$owner === null ||
Craft::$app->getView()->renderObjectTemplate($this->propagationKeyFormat, $owner) !== ''
);
}
return $this->propagationMethod !== PropagationMethod::All;
}
private function nestedElementQuery(ElementInterface $owner): ElementQueryInterface
{
return call_user_func($this->queryFactory, $owner);
}
private function getValue(ElementInterface $owner, bool $fetchAll = false): ElementQueryInterface|ElementCollection
{
if (isset($this->valueGetter)) {
return call_user_func($this->valueGetter, $owner, $fetchAll);
}
if (isset($this->attribute)) {
return $owner->{$this->attribute};
}
$query = $owner->getFieldValue($this->field->handle);
if ($query instanceof ElementCollection) {
return $query;
}
if (!$query instanceof ElementQueryInterface) {
$query = $this->nestedElementQuery($owner);
}
if ($fetchAll && $query->getCachedResult() === null) {
$query
->drafts(null)
->canonicalsOnly()
->savedDraftsOnly()
->status(null)
->limit(null);
}
return $query;
}
private function setValue(ElementInterface $owner, ElementQueryInterface|ElementCollection $value): void
{
if ($this->valueSetter === false) {
return;
}
if (isset($this->valueSetter)) {
call_user_func($this->valueSetter, $value, $owner);
} elseif (isset($this->attribute)) {
$owner->{$this->attribute} = $value;
} else {
$owner->setFieldValue($this->field->handle, $value);
}
}
/**
* @param ElementInterface $owner
* @param NestedElementInterface[] $elements
*/
private function setOwnerOnNestedElements(ElementInterface $owner, array $elements): void
{
foreach ($elements as $element) {
$element->setOwner($owner);
if ($owner->id === $element->getPrimaryOwnerId()) {
$element->setPrimaryOwner($owner);
}
}
}
/**
* Returns the search keywords for nested elements of the given owner element.
*
* @param ElementInterface $owner
* @return string
*/
public function getSearchKeywords(ElementInterface $owner): string
{
$keywords = [];
/** @var NestedElementInterface[] $elements */
$elements = $this->getValue($owner)->all();
$this->setOwnerOnNestedElements($owner, $elements);
foreach ($elements as $element) {
$hasTitles ??= $element::hasTitles();
if ($hasTitles) {
$keywords[] = $element->title;
}
foreach ($element->getFieldLayout()->getCustomFields() as $field) {
if ($field->searchable) {
$fieldValue = $element->getFieldValue($field->handle);
$keywords[] = $field->getSearchKeywords($fieldValue, $element);
}
}
}
return StringHelper::toString($keywords, ' ');
}
/**
* Returns the description of this field or attribute’s translation support, for the given owner element.
*
* @param ElementInterface|null $owner
* @return string|null
*/
public function getTranslationDescription(?ElementInterface $owner = null): ?string
{
if (!$owner) {
return null;
}
switch ($this->propagationMethod) {
case PropagationMethod::None:
return Craft::t('app', '{type} will only be saved in the {site} site.', [
'type' => $this->elementType::pluralDisplayName(),
'site' => Craft::t('site', $owner->getSite()->getName()),
]);
case PropagationMethod::SiteGroup:
return Craft::t('app', '{type} will be saved across all sites in the {group} site group.', [
'type' => $this->elementType::pluralDisplayName(),
'group' => Craft::t('site', $owner->getSite()->getGroup()->getName()),
]);
case PropagationMethod::Language:
$language = Craft::$app->getI18n()->getLocaleById($owner->getSite()->language)
->getDisplayName(Craft::$app->language);
return Craft::t('app', '{type} will be saved across all {language}-language sites.', [
'type' => $this->elementType::pluralDisplayName(),
'language' => $language,
]);
default:
return null;
}
}
/**
* Returns the site IDs that are supported by nested elements for the given owner element.
*
* @param ElementInterface $owner
* @return int[]
* @since 5.0.0
*/
public function getSupportedSiteIds(ElementInterface $owner): array
{
/** @var Site[] $allSites */
$allSites = ArrayHelper::index(Craft::$app->getSites()->getAllSites(), 'id');
$ownerSiteIds = array_map(
fn(array $siteInfo) => $siteInfo['siteId'],
ElementHelper::supportedSitesForElement($owner),
);
$siteIds = [];
$view = Craft::$app->getView();
$elementsService = Craft::$app->getElements();
if ($this->propagationMethod === PropagationMethod::Custom && $this->propagationKeyFormat !== null) {
$cacheKey = sprintf('%s-%s-%s', md5($this->propagationKeyFormat), $owner->id, $owner->siteId);
if (!isset(self::$renderedPropagationFormats[$cacheKey])) {
self::$renderedPropagationFormats[$cacheKey] = $view->renderObjectTemplate($this->propagationKeyFormat, $owner);
}
$propagationKey = self::$renderedPropagationFormats[$cacheKey];
}
foreach ($ownerSiteIds as $siteId) {
switch ($this->propagationMethod) {
case PropagationMethod::None:
$include = $siteId == $owner->siteId;
break;
case PropagationMethod::SiteGroup:
$include = $allSites[$siteId]->groupId == $allSites[$owner->siteId]->groupId;
break;
case PropagationMethod::Language:
$include = $allSites[$siteId]->language == $allSites[$owner->siteId]->language;
break;
case PropagationMethod::Custom:
if (!isset($propagationKey)) {
$include = true;
} else {
$cacheKey = sprintf('%s-%s-%s', md5($this->propagationKeyFormat), $owner->id, $siteId);
if (!isset(self::$renderedPropagationFormats[$cacheKey])) {
$siteOwner = $elementsService->getElementById($owner->id, get_class($owner), $siteId);
self::$renderedPropagationFormats[$cacheKey] = $siteOwner
? $view->renderObjectTemplate($this->propagationKeyFormat, $siteOwner)
: false;
}
$include = $propagationKey === self::$renderedPropagationFormats[$cacheKey];
}
break;
default:
$include = true;
break;
}
if ($include) {
$siteIds[] = $siteId;
}
}
return $siteIds;
}
/**
* Returns the HTML for managing nested elements via cards.
*
* @param ElementInterface|null $owner
* @param array $config
* @return string
*/
public function getCardsHtml(?ElementInterface $owner, array $config = []): string
{
$config += [
'showInGrid' => false,
'prevalidate' => false,
'selectable' => false,
];
return $this->createView(
$owner,
$config,
self::VIEW_MODE_CARDS,
function(string $id, array $config, $attribute, &$settings) use ($owner) {
$settings += [
'deleteLabel' => StringHelper::upperCaseFirst(Craft::t('app', 'Delete {type}', [
'type' => $this->elementType::lowerDisplayName(),
])),
'deleteConfirmationMessage' => Craft::t('app', 'Are you sure you want to delete the selected {type}?', [
'type' => $this->elementType::lowerDisplayName(),
]),
'showInGrid' => $config['showInGrid'],
'selectable' => $config['selectable'],
];
$html = Html::beginTag('div', options: [
'id' => $id,
'class' => 'nested-element-cards',
]);
/** @var ElementQueryInterface|ElementCollection $value */
$value = $this->getValue($owner, true);
if ($value instanceof ElementCollection) {
/** @var NestedElementInterface[] $elements */
$elements = $value->all();
} else {
/** @var NestedElementInterface[] $elements */
$elements = $value->getCachedResult() ?? $value
->status(null)
->limit(null)
->all();
}
// See if there are any provisional changes we should show
ElementHelper::loadProvisionalChanges($elements);
if ($this->hasErrors($owner)) {
foreach ($elements as $element) {
if ($element->enabled && $element->getEnabledForSite()) {
$element->setScenario(Element::SCENARIO_LIVE);
}
$element->validate();
}
}
$this->setOwnerOnNestedElements($owner, $elements);
if (!empty($elements)) {
$html .= Html::ul(array_map(
fn(ElementInterface $element) => Cp::elementCardHtml($element, [
'context' => 'field',
'showActionMenu' => true,
'selectable' => $config['selectable'],
'sortable' => $config['sortable'],
'showInGrid' => $config['showInGrid'] ?? false,
]),
$elements,
), [
'encode' => false,
'class' => [
'elements',
$config['showInGrid'] ? 'card-grid' : 'cards',
$config['prevalidate'] ? 'prevalidate' : '',
],
]);
}
$html .=
Html::tag('div', Craft::t('app', 'Nothing yet.'), [
'class' => array_keys(array_filter([
'pane' => true,
'no-border' => true,
'zilch' => true,
'small' => true,
'hidden' => !empty($elements),
])),
]) .
Html::endTag('div');
return $html;
}
);
}
/**
* Returns the HTML for managing nested elements via an element index.
*
* @param ElementInterface|null $owner
* @param array $config
* @return string
*/
public function getIndexHtml(?ElementInterface $owner, array $config = []): string
{
$config += [
'allowedViewModes' => null,
'showHeaderColumn' => true,
'fieldLayouts' => [],
'defaultSort' => null,
'defaultTableColumns' => null,
'prevalidate' => false,
'pageSize' => 50,
'storageKey' => null,
'defaultViewMode' => 'cards',
'static' => $owner->getIsRevision(),
];
if ($config['storageKey'] === null) {
if (isset($this->field)) {
if ($this->field::isMultiInstance()) {
if (isset($this->field->layoutElement)) {
$config['storageKey'] = sprintf('field:%s', $this->field->layoutElement->uid);
}
} else {
$config['storageKey'] = sprintf('field:%s', $this->field->uid);
}
} elseif ($owner !== null) {
$config['storageKey'] = sprintf('%s:%s', $owner::class, $this->attribute);
}
}
return $this->createView(
$owner,
$config,
self::VIEW_MODE_INDEX,
function(string $id, array $config, string $attribute, array &$settings) use ($owner): string {
$view = Craft::$app->getView();
$criteria = [
$this->ownerIdParam => $owner->id,
];
if ($owner->getIsRevision()) {
$criteria['revisions'] = null;
$criteria['trashed'] = null;
$criteria['drafts'] = false;
}
$settings['indexSettings'] = [
'namespace' => $view->getNamespace(),
'allowedViewModes' => $config['allowedViewModes']
? array_map(fn($mode) => StringHelper::toString($mode), $config['allowedViewModes'])
: null,
'showHeaderColumn' => $config['showHeaderColumn'],
'criteria' => array_merge($criteria, $this->criteria),
'batchSize' => $config['pageSize'],
'actions' => [],
'canHaveDrafts' => $config['canHaveDrafts'] ?? $this->elementType::hasDrafts(),
'storageKey' => $config['storageKey'],
'static' => $config['static'],
];
if (!$config['static'] && $config['sortable']) {
$view->startJsBuffer();
$actionConfig = ElementHelper::actionConfig(new ChangeSortOrder($owner, $attribute));
$actionConfig['bodyHtml'] = $view->clearJsBuffer();
$settings['indexSettings']['actions'][] = $actionConfig;
$view->startJsBuffer();
$actionConfig = ElementHelper::actionConfig(new MoveUp($owner, $attribute));
$actionConfig['bodyHtml'] = $view->clearJsBuffer();
$settings['indexSettings']['actions'][] = $actionConfig;
$view->startJsBuffer();
$actionConfig = ElementHelper::actionConfig(new MoveDown($owner, $attribute));
$actionConfig['bodyHtml'] = $view->clearJsBuffer();
$settings['indexSettings']['actions'][] = $actionConfig;
}
return Cp::elementIndexHtml($this->elementType, [
'class' => [$config['prevalidate'] ? 'prevalidate' : ''],
'context' => 'embedded-index',
'defaultSort' => $config['defaultSort'],
'defaultTableColumns' => $config['defaultTableColumns'],
'defaultViewMode' => $config['defaultViewMode'],
'fieldLayouts' => $config['fieldLayouts'],
'id' => $id,
'prevalidate' => $config['prevalidate'] ?? false,
'registerJs' => false,
'showSiteMenu' => false,
'sources' => false,
]);
},
);
}
private function createView(?ElementInterface $owner, array $config, string $mode, callable $renderHtml): string
{
if (!$owner?->id) {
$message = Craft::t('app', '{nestedType} can only be created after the {ownerType} has been saved.', [
'nestedType' => $this->elementType::pluralDisplayName(),
'ownerType' => $owner ? $owner::lowerDisplayName() : Craft::t('app', 'element'),
]);
return Html::tag('div', $message, ['class' => 'pane no-border zilch small']);
}
$config += [
'sortable' => false,
'canCreate' => false,
'canPaste' => false,
'createButtonLabel' => null,
'createAttributes' => null,
'minElements' => null,
'maxElements' => null,
];
if ($config['createButtonLabel'] === null) {
$config['createButtonLabel'] = Craft::t('app', 'New {type}', [
'type' => $this->elementType::lowerDisplayName(),
]);
}
$authorizedOwnerId = $owner->id;
if ($owner->isProvisionalDraft) {
/** @var ElementInterface&DraftBehavior $owner */
if ($owner->creatorId === Craft::$app->getUser()->getIdentity()?->id) {
$authorizedOwnerId = $owner->getCanonicalId();
}
}
$attribute = $this->attribute ?? sprintf('field:%s', $this->field->handle);
Craft::$app->getSession()->authorize(sprintf('manageNestedElements::%s::%s', $authorizedOwnerId, $attribute));
$view = Craft::$app->getView();
return $view->namespaceInputs(function() use (
$mode,
$attribute,
$view,
$owner,
$config,
$renderHtml,
) {
$id = sprintf('element-index-%s', mt_rand());
$settings = [
'mode' => $mode,
'ownerElementType' => $owner::class,
'ownerId' => $owner->id,
'ownerSiteId' => $owner->siteId,
'attribute' => $attribute,
'sortable' => $config['sortable'],
'canCreate' => $config['canCreate'],
'canPaste' => $config['canPaste'],
'minElements' => $config['minElements'],
'maxElements' => $config['maxElements'],
'createButtonLabel' => $config['createButtonLabel'],
'ownerIdParam' => $this->ownerIdParam,
'fieldId' => $this->field?->id,
'fieldHandle' => $this->field?->handle,
'baseInputName' => $view->getNamespace(),
'prevalidate' => $config['prevalidate'] ?? false,
];
if (!empty($config['createAttributes'])) {
$settings['createAttributes'] = $config['createAttributes'];
if (ArrayHelper::isIndexed($settings['createAttributes'])) {
if (count($settings['createAttributes']) === 1) {
$settings['createAttributes'] = ArrayHelper::firstValue($settings['createAttributes'])['attributes'];
} else {
$settings['createAttributes'] = array_map(function(array $attributes) {
if (isset($attributes['icon'])) {
$attributes['icon'] = Cp::iconSvg($attributes['icon']);
}
if (isset($attributes['color']) && $attributes['color'] instanceof Color) {
$attributes['color'] = $attributes['color']->value;
}
return $attributes;
}, $settings['createAttributes']);
}
}
}
// render the HTML, and give the render function a chance to modify the JS settings
$html = $renderHtml($id, $config, $attribute, $settings);
$view->registerJsWithVars(fn($id, $elementType, $settings) => <<<JS
(() => {
new Craft.NestedElementManager('#' + $id, $elementType, $settings);
})();
JS, [
$view->namespaceInputId($id),
$this->elementType,
$settings,
]);
return $html;
}, Html::id($this->field->handle ?? $attribute));
}
/**
* Maintains the nested elements after an owner element has been saved.
*
* This should be called from the element’s [[ElementInterface::afterPropagate()|afterPropagate()]] method,
* or the field’s [[\craft\base\FieldInterface::afterElementPropagate()|afterElementPropagate()]] method.
*
* @param ElementInterface $owner
* @param bool $isNew Whether the owner is a new element
*/
public function maintainNestedElements(ElementInterface $owner, bool $isNew): void
{
$resetValue = false;
if ($owner->duplicateOf !== null) {
// If this is a draft, its nested element ownership will be duplicated by Drafts::createDraft()
if ($owner->getIsRevision()) {
$this->createRevisions($owner->duplicateOf, $owner);
// getIsUnpublishedDraft is needed for "save as new" duplication
} elseif (!$owner->getIsDraft() || $owner->getIsUnpublishedDraft()) {
$this->duplicateNestedElements($owner->duplicateOf, $owner, true, !$isNew);
}
$resetValue = true;
} elseif (
$this->isDirty($owner) ||
$this->propagateRequired($owner) ||
!empty($owner->newSiteIds)
) {
$this->saveNestedElements($owner);
} elseif ($owner->mergingCanonicalChanges) {
$this->mergeCanonicalChanges($owner);
$resetValue = true;
}
// Always reset the value if the owner is new
if ($isNew || $resetValue) {
$dirtyFields = $owner->getDirtyFields();
$this->setValue($owner, $this->nestedElementQuery($owner));
$owner->setDirtyFields($dirtyFields, false);
}
}
private function isDirty(ElementInterface $owner): bool
{
if (isset($this->attribute)) {
return $owner->isAttributeDirty($this->attribute);
}
foreach ($this->fieldInstances($owner) as $instance) {
/** @var FieldInterface $instance */
if ($owner->isFieldDirty($instance->handle)) {
return true;
}
}
return false;
}
private function isModified(ElementInterface $owner, bool $anySite = false): bool
{
if (isset($this->attribute)) {
return $owner->isAttributeModified($this->attribute);
}
foreach ($this->fieldInstances($owner) as $instance) {
/** @var FieldInterface $instance */
if ($owner->isFieldModified($instance->handle, $anySite)) {
return true;
}
}
return false;
}
private function hasErrors(ElementInterface $owner): bool
{
if (isset($this->attribute)) {
return $owner->hasErrors("$this->attribute.*");
}
foreach ($this->fieldInstances($owner) as $instance) {
/** @var FieldInterface $instance */
if ($owner->hasErrors("$instance->handle.*")) {
return true;
}
}
return false;
}
private function fieldInstances(ElementInterface $owner): Generator
{
if (!isset($this->field)) {
return;
}
if (!$this->field::isMultiInstance()) {
yield $this->field;
return;
}
$customFields = $owner->getFieldLayout()?->getCustomFields() ?? [];
foreach ($customFields as $field) {
if ($field->id === $this->field->id) {
yield $field;
}
}
}
private function propagateRequired(ElementInterface $owner, ?ElementInterface $localizedOwner = null): bool
{
foreach ($this->fieldInstances($owner) as $instance) {
if (
$instance->layoutElement->required &&
(
!$localizedOwner ||
$instance->isValueEmpty($localizedOwner->getFieldValue($instance->handle), $localizedOwner)
)
) {
return true;
}
}
return false;
}
private function saveNestedElements(ElementInterface $owner): void
{
$elementsService = Craft::$app->getElements();
$value = $this->getValue($owner, true);
if ($value instanceof ElementCollection) {
$elements = $value->all();
$saveAll = true;
} else {
$elements = $value->getCachedResult();
if ($elements !== null) {
$saveAll = !empty($owner->newSiteIds);
} else {
$elements = $value->all();
$saveAll = true;
}
}
/** @var NestedElementInterface[] $elements */
$this->setOwnerOnNestedElements($owner, $elements);
$elementIds = [];
$sortOrder = 0;
$managerKey = isset($this->field)
? sprintf('field:%s', (string)($this->field->uid ?? $this->field->handle ?? $this->field->id))
: sprintf('attribute:%s', (string)$this->attribute);
$transaction = Craft::$app->getDb()->beginTransaction();
try {
/** @var NestedElementInterface[] $elements */
foreach ($elements as $element) {
// If it's soft-deleted, restore it.
// (This could happen if the element didn't come back in getValue() previously,
// but now it's showing up again, e.g. if an entry card was cut from a CKEditor field
// and then pasted back in somewhere else.)
if (isset($element->dateDeleted)) {
$elementsService->restoreElement($element);
}
// if the owner is propagating required fields and attributes, so should the nested elements
if ($owner->propagateRequired) {
$element->propagateRequired = true;
}
$sortOrder++;
$shouldSave = $saveAll || !$element->id || $element->forceSave;
if (
$shouldSave &&
isset($element->id) &&
!$elementsService->shouldSaveNestedElement($owner, $element, $managerKey, $sortOrder)
) {
$shouldSave = false;
}
if ($shouldSave) {
$element->setOwner($owner);
$element->setSortOrder($sortOrder);
$element->resaving = $owner->resaving;
$elementsService->saveElement($element, false);
// If this element's primary owner is $owner, and it’s a draft of another element whose owner is
// $owner's canonical (e.g. a draft entry created by Matrix::_createEntriesFromSerializedData()),
// we can shed its draft data and relation with the canonical owner now
if (
$element->getPrimaryOwnerId() === $owner->id &&
$element->getIsDraft() &&
!$element->getIsUnpublishedDraft() &&
// $owner could be a draft or a non-canonical Matrix entry, etc.
(!$owner->getIsCanonical()) &&
!$owner->getIsUnpublishedDraft()
) {
/** @var NestedElementInterface $canonical */
$canonical = $element->getCanonical(true);
if ($canonical->getPrimaryOwnerId() === $owner->getCanonicalId()) {
Craft::$app->getDrafts()->removeDraftData($element);
Db::delete(Table::ELEMENTS_OWNERS, [
'elementId' => $canonical->id,
'ownerId' => $owner->id,
]);
}
} elseif (
$element->getIsUnpublishedDraft() &&
$element->getPrimaryOwnerId() === $owner->id
) {
Craft::$app->getDrafts()->removeDraftData($element);
}
} elseif ((int)$element->getSortOrder() !== $sortOrder) {
// Just update its sortOrder
$element->setSortOrder($sortOrder);
Db::update(Table::ELEMENTS_OWNERS, [
'sortOrder' => $sortOrder,
], [
'elementId' => $element->id,
'ownerId' => $owner->id,
], [], false);
}
$elementIds[] = $element->id;
}
// Delete any elements that shouldn't be there anymore
$this->deleteOtherNestedElements($owner, $elementIds);
// Should we duplicate the elements to other sites?
if (
$this->propagationMethod !== PropagationMethod::All &&
(
$owner->propagateAll ||
$this->propagateRequired($owner) ||
!empty($owner->newSiteIds)
)
) {
// Find the owner's site IDs that *aren't* supported by this site's nested elements
$ownerSiteIds = array_map(
fn(array $siteInfo) => $siteInfo['siteId'],
ElementHelper::supportedSitesForElement($owner),
);
$fieldSiteIds = $this->getSupportedSiteIds($owner);
$otherSiteIds = array_diff($ownerSiteIds, $fieldSiteIds);
// If propagateAll & propagateRequired aren't set, only deal with sites that the element was just propagated to for the first time
if (!$owner->propagateAll && !$this->propagateRequired($owner)) {
$preexistingOtherSiteIds = array_diff($otherSiteIds, $owner->newSiteIds);
$otherSiteIds = array_intersect($otherSiteIds, $owner->newSiteIds);
} else {
$preexistingOtherSiteIds = [];
}
if (!empty($otherSiteIds)) {
// Get the owner element across each of those sites
$localizedOwners = $owner::find()
->drafts($owner->getIsDraft())
->provisionalDrafts($owner->isProvisionalDraft)
->revisions($owner->getIsRevision())
->id($owner->id)
->siteId($otherSiteIds)
->status(null)
->all();
// Duplicate elements, ensuring we don't process the same elements more than once
$handledSiteIds = [];
if ($value instanceof ElementQueryInterface) {
$cachedQuery = (clone $value)->status(null);
$cachedQuery->setCachedResult($elements);
$this->setValue($owner, $cachedQuery);
}
foreach ($localizedOwners as $localizedOwner) {
// Make sure we haven't already duplicated elements for this site, via propagation from another site
if (isset($handledSiteIds[$localizedOwner->siteId])) {
continue;
}
// Find all the source owner’s supported sites
$sourceSupportedSiteIds = $this->getSupportedSiteIds($localizedOwner);
// Do elements in this target happen to share supported sites with a preexisting site?
if (
!empty($preexistingOtherSiteIds) &&
!empty($sharedPreexistingOtherSiteIds = array_intersect($preexistingOtherSiteIds, $sourceSupportedSiteIds)) &&
$preexistingLocalizedOwner = $owner::find()
->drafts($owner->getIsDraft())
->provisionalDrafts($owner->isProvisionalDraft)
->revisions($owner->getIsRevision())
->id($owner->id)
->siteId($sharedPreexistingOtherSiteIds)
->status(null)
->one()
) {
// Just resave elements for that one site, and let them propagate over to the new site(s) from there
$this->saveNestedElements($preexistingLocalizedOwner);
} else {
// Duplicate the elements, but **don't track** the duplications, so the edit page doesn’t think
// its elements have been replaced by the other sites’ nested elements
if ($owner->propagateAll || $this->propagateRequired($owner, $localizedOwner)) {
$this->duplicateNestedElements($owner, $localizedOwner, force: true);
}
}
// Make sure we don't duplicate elements for any of the sites that were just propagated to
foreach ($sourceSupportedSiteIds as $siteId) {
$handledSiteIds[$siteId] = true;
}
}
if ($value instanceof ElementQueryInterface) {
$this->setValue($owner, $value);
}
}
}
$transaction->commit();
} catch (Throwable $e) {
$transaction->rollBack();
throw $e;