-
Notifications
You must be signed in to change notification settings - Fork 690
Expand file tree
/
Copy pathFields.php
More file actions
1660 lines (1443 loc) · 52.4 KB
/
Fields.php
File metadata and controls
1660 lines (1443 loc) · 52.4 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\services;
use Craft;
use craft\base\ElementContainerFieldInterface;
use craft\base\ElementInterface;
use craft\base\Field;
use craft\base\FieldInterface;
use craft\base\FieldLayoutElement;
use craft\base\Iconic;
use craft\base\MemoizableArray;
use craft\behaviors\CustomFieldBehavior;
use craft\db\FixedOrderExpression;
use craft\db\Query;
use craft\db\Table;
use craft\errors\MissingComponentException;
use craft\events\ApplyFieldSaveEvent;
use craft\events\ConfigEvent;
use craft\events\DefineCompatibleFieldTypesEvent;
use craft\events\FieldEvent;
use craft\events\FieldLayoutEvent;
use craft\events\RegisterComponentTypesEvent;
use craft\fieldlayoutelements\BaseField;
use craft\fieldlayoutelements\CustomField;
use craft\fields\Addresses as AddressesField;
use craft\fields\Assets as AssetsField;
use craft\fields\BaseRelationField;
use craft\fields\ButtonGroup;
use craft\fields\Categories as CategoriesField;
use craft\fields\Checkboxes;
use craft\fields\Color;
use craft\fields\ContentBlock;
use craft\fields\Country;
use craft\fields\Date;
use craft\fields\Dropdown;
use craft\fields\Email;
use craft\fields\Entries as EntriesField;
use craft\fields\Icon;
use craft\fields\Json;
use craft\fields\Lightswitch;
use craft\fields\Link;
use craft\fields\Matrix as MatrixField;
use craft\fields\MissingField;
use craft\fields\Money;
use craft\fields\MultiSelect;
use craft\fields\Number;
use craft\fields\PlainText;
use craft\fields\RadioButtons;
use craft\fields\Range;
use craft\fields\Table as TableField;
use craft\fields\Tags as TagsField;
use craft\fields\Time;
use craft\fields\Users as UsersField;
use craft\helpers\AdminTable;
use craft\helpers\ArrayHelper;
use craft\helpers\Component as ComponentHelper;
use craft\helpers\Cp;
use craft\helpers\Db;
use craft\helpers\Json as JsonHelper;
use craft\helpers\ProjectConfig as ProjectConfigHelper;
use craft\helpers\StringHelper;
use craft\models\FieldLayout;
use craft\models\FieldLayoutTab;
use craft\records\Field as FieldRecord;
use craft\records\FieldLayout as FieldLayoutRecord;
use DateTime;
use Illuminate\Support\Collection;
use Throwable;
use yii\base\Component;
use yii\base\Exception;
use yii\base\InvalidArgumentException;
use yii\web\BadRequestHttpException;
/**
* Fields service.
*
* An instance of the service is available via [[\craft\base\ApplicationTrait::getFields()|`Craft::$app->getFields()`]].
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
class Fields extends Component
{
/**
* @event RegisterComponentTypesEvent The event that is triggered when registering field types.
*
* Field types must implement [[FieldInterface]]. [[Field]] provides a base implementation.
*
* See [Field Types](https://craftcms.com/docs/5.x/extend/field-types.html) for documentation on creating field types.
* ---
* ```php
* use craft\events\RegisterComponentTypesEvent;
* use craft\services\Fields;
* use yii\base\Event;
*
* Event::on(Fields::class,
* Fields::EVENT_REGISTER_FIELD_TYPES,
* function(RegisterComponentTypesEvent $event) {
* $event->types[] = MyFieldType::class;
* }
* );
* ```
*/
public const EVENT_REGISTER_FIELD_TYPES = 'registerFieldTypes';
/**
* @event RegisterComponentTypesEvent The event that is triggered when registering field types which manage nested entries.
*
* These field types must implement [[ElementContainerFieldInterface]].
*
* @since 5.0.0
*/
public const EVENT_REGISTER_NESTED_ENTRY_FIELD_TYPES = 'registerNestedEntryFieldTypes';
/**
* @event DefineCompatibleFieldTypesEvent The event that is triggered when defining the compatible field types for a field.
* @see getCompatibleFieldTypes()
* @since 4.5.7
*/
public const EVENT_DEFINE_COMPATIBLE_FIELD_TYPES = 'defineCompatibleFieldTypes';
/**
* @event FieldEvent The event that is triggered before a field is saved.
*/
public const EVENT_BEFORE_SAVE_FIELD = 'beforeSaveField';
/**
* @event ApplyFieldSaveEvent The event that is triggered before a field save is applied to the database.
* @since 5.5.0
*/
public const EVENT_BEFORE_APPLY_FIELD_SAVE = 'beforeApplyFieldSave';
/**
* @event FieldEvent The event that is triggered after a field is saved.
*/
public const EVENT_AFTER_SAVE_FIELD = 'afterSaveField';
/**
* @event FieldEvent The event that is triggered before a field is deleted.
*/
public const EVENT_BEFORE_DELETE_FIELD = 'beforeDeleteField';
/**
* @event FieldEvent The event that is triggered before a field delete is applied to the database.
* @since 3.1.0
*/
public const EVENT_BEFORE_APPLY_FIELD_DELETE = 'beforeApplyFieldDelete';
/**
* @event FieldEvent The event that is triggered after a field is deleted.
*/
public const EVENT_AFTER_DELETE_FIELD = 'afterDeleteField';
/**
* @event FieldLayoutEvent The event that is triggered before a field layout is saved.
*/
public const EVENT_BEFORE_SAVE_FIELD_LAYOUT = 'beforeSaveFieldLayout';
/**
* @event FieldLayoutEvent The event that is triggered after a field layout is saved.
*/
public const EVENT_AFTER_SAVE_FIELD_LAYOUT = 'afterSaveFieldLayout';
/**
* @event FieldLayoutEvent The event that is triggered before a field layout is deleted.
*/
public const EVENT_BEFORE_DELETE_FIELD_LAYOUT = 'beforeDeleteFieldLayout';
/**
* @event FieldLayoutEvent The event that is triggered after a field layout is deleted.
*/
public const EVENT_AFTER_DELETE_FIELD_LAYOUT = 'afterDeleteFieldLayout';
/**
* @var string The active field context
* @since 5.0.0
*/
public string $fieldContext = 'global';
/**
* @var MemoizableArray<FieldInterface>|null
* @see _fields()
*/
private ?MemoizableArray $_fields = null;
/**
* @var MemoizableArray<FieldLayout>|null
* @see _layouts()
*/
private ?MemoizableArray $_layouts = null;
/**
* @var array
*/
private array $_savingFields = [];
/**
* Serializer
*
* @since 3.5.14
*/
public function __serialize()
{
$vars = get_object_vars($this);
unset($vars['_fields']);
return $vars;
}
// Fields
// -------------------------------------------------------------------------
/**
* Returns all available field type classes.
*
* @return string[] The available field type classes
* @phpstan-return class-string<FieldInterface>[]
*/
public function getAllFieldTypes(): array
{
$fieldTypes = [
AddressesField::class,
AssetsField::class,
ButtonGroup::class,
CategoriesField::class,
Checkboxes::class,
Color::class,
ContentBlock::class,
Country::class,
Date::class,
Dropdown::class,
Email::class,
EntriesField::class,
Icon::class,
Json::class,
Lightswitch::class,
Link::class,
MatrixField::class,
Money::class,
MultiSelect::class,
Number::class,
PlainText::class,
RadioButtons::class,
Range::class,
TableField::class,
TagsField::class,
Time::class,
UsersField::class,
];
// Fire a 'registerFieldTypes' event
if ($this->hasEventHandlers(self::EVENT_REGISTER_FIELD_TYPES)) {
$event = new RegisterComponentTypesEvent(['types' => $fieldTypes]);
$this->trigger(self::EVENT_REGISTER_FIELD_TYPES, $event);
return $event->types;
}
return $fieldTypes;
}
/**
* Returns all field types that have a column in the content table.
*
* @return string[] The field type classes
* @phpstan-return class-string<FieldInterface>[]
*/
public function getFieldTypesWithContent(): array
{
return ArrayHelper::where(
$this->getAllFieldTypes(),
fn(string $class) => /** @var class-string<FieldInterface> $class */ $class::dbType() !== null,
keepKeys: false,
);
}
/**
* Returns all field types whose column types are considered compatible with a given field.
*
* @param FieldInterface $field The current field to base compatible fields on
* @param bool $includeCurrent Whether $field's class should be included
* @return string[] The compatible field type classes
* @phpstan-return class-string<FieldInterface>[]
*/
public function getCompatibleFieldTypes(FieldInterface $field, bool $includeCurrent = true): array
{
// If the field has any validation errors and has an ID, swap it with the saved field
if (!$field->getIsNew() && $field->hasErrors()) {
$field = $this->getFieldById($field->id);
}
$types = [];
$dbType = $field::dbType();
if (is_string($dbType)) {
foreach ($this->getAllFieldTypes() as $class) {
/** @var class-string<FieldInterface> $class */
if (
($includeCurrent || $class !== $field::class) &&
$this->areFieldTypesCompatible($field::class, $class)
) {
$types[] = $class;
}
}
}
// Make sure the current field class is in there if it's supposed to be
/** @var FieldInterface $field */
if ($includeCurrent && !in_array(get_class($field), $types, true)) {
$types[] = get_class($field);
}
// Fire a 'defineCompatibleFieldTypes' event
if ($this->hasEventHandlers(self::EVENT_DEFINE_COMPATIBLE_FIELD_TYPES)) {
$event = new DefineCompatibleFieldTypesEvent([
'field' => $field,
'compatibleTypes' => $types,
]);
$this->trigger(self::EVENT_DEFINE_COMPATIBLE_FIELD_TYPES, $event);
return $event->compatibleTypes;
}
return $types;
}
/**
* Returns whether the two given field types are considered compatible with each other.
*
* @param class-string<FieldInterface> $fieldA
* @param class-string<FieldInterface> $fieldB
* @return bool
* @since 5.3.0
*/
public function areFieldTypesCompatible(string $fieldA, string $fieldB): bool
{
if ($fieldA === $fieldB) {
return true;
}
$dbTypeA = $fieldA::dbType();
if (!is_string($dbTypeA)) {
return false;
}
$dbTypeB = $fieldB::dbType();
if (!is_string($dbTypeB)) {
return false;
}
return Db::areColumnTypesCompatible($dbTypeA, $dbTypeB);
}
/**
* Returns all field types which manage nested entries.
*
* @return string[] The field type classes which manage nested entries
* @phpstan-return class-string<ElementContainerFieldInterface>[]
*/
public function getNestedEntryFieldTypes(): array
{
$fieldTypes = [
MatrixField::class,
];
// Fire a 'registerNestedEntryFieldTypes' event
if ($this->hasEventHandlers(self::EVENT_REGISTER_NESTED_ENTRY_FIELD_TYPES)) {
$event = new RegisterComponentTypesEvent(['types' => $fieldTypes]);
$this->trigger(self::EVENT_REGISTER_NESTED_ENTRY_FIELD_TYPES, $event);
return $event->types;
}
return $fieldTypes;
}
/**
* Returns all available relational field type classes.
*
* @return string[] The available relational field type classes
* @phpstan-return class-string<BaseRelationField>[]
* @since 5.1.6
*/
public function getRelationalFieldTypes(): array
{
$relationalFields = [];
foreach ($this->getAllFieldTypes() as $fieldClass) {
if (is_subclass_of($fieldClass, BaseRelationField::class)) {
$relationalFields[] = $fieldClass;
}
}
return $relationalFields;
}
/**
* Creates a field with a given config.
*
* @template T of FieldInterface
* @param class-string<T>|array $config The field’s class name, or its config, with a `type` value and optionally a `settings` value
* @phpstan-param class-string<T>|array{type:class-string<T>,id?:int|string,uid?:string} $config
* @return T The field
*/
public function createField(mixed $config): FieldInterface
{
if (is_string($config)) {
$config = ['type' => $config];
}
if (!empty($config['id']) && empty($config['uid']) && is_numeric($config['id'])) {
$uid = Db::uidById(Table::FIELDS, $config['id']);
$config['uid'] = $uid;
}
try {
$field = ComponentHelper::createComponent($config, FieldInterface::class);
} catch (MissingComponentException $e) {
$config['errorMessage'] = $e->getMessage();
$config['expectedType'] = $config['type'];
unset($config['type']);
$field = new MissingField($config);
}
return $field;
}
/**
* Returns a memoizable array of fields.
*
* @param string|string[]|false|null $context The field context(s) to fetch fields from. Defaults to [[\craft\services\Fields::$fieldContext]].
* Set to `false` to get all fields regardless of context.
*
* @return MemoizableArray<FieldInterface>
*/
private function _fields(mixed $context = null): MemoizableArray
{
$context ??= $this->fieldContext;
if (!isset($this->_fields)) {
$this->_fields = new MemoizableArray(
$this->_createFieldQuery()->all(),
fn(array $config) => $this->createField($config),
);
}
if ($context === false) {
return $this->_fields;
}
if (is_array($context)) {
return $this->_fields->whereIn('context', $context, true);
}
return $this->_fields->where('context', $context, true);
}
/**
* Returns all fields within a field context(s).
*
* @param string|string[]|false|null $context The field context(s) to fetch fields from. Defaults to [[\craft\services\Fields::$fieldContext]].
* Set to `false` to get all fields regardless of context.
* @return FieldInterface[] The fields
*/
public function getAllFields(mixed $context = null): array
{
return $this->_fields($context)->all();
}
/**
* Returns all fields that store content in the `elements_sites.content` table.
*
* @param string|string[]|false|null $context The field context(s) to fetch fields from. Defaults to [[\craft\services\Fields::$fieldContext]].
* Set to `false` to get all fields regardless of context.
* @return FieldInterface[] The fields
*/
public function getFieldsWithContent(mixed $context = null): array
{
return ArrayHelper::where(
$this->getAllFields($context),
fn(FieldInterface $field) => $field::dbType() !== null,
keepKeys: false,
);
}
/**
* Returns all fields that don’t store content in the `elements_sites.content` table.
*
* @param string|string[]|false|null $context The field context(s) to fetch fields from. Defaults to [[\craft\services\Fields::$fieldContext]].
* Set to `false` to get all fields regardless of context.
* @return FieldInterface[] The fields
* @since 4.3.2
*/
public function getFieldsWithoutContent(mixed $context = null): array
{
return ArrayHelper::where(
$this->getAllFields($context),
fn(FieldInterface $field) => $field::dbType() === null,
keepKeys: false,
);
}
/**
* Returns all fields of a certain type.
*
* @param class-string<FieldInterface> $type The field type
* @param string|string[]|false|null $context The field context(s) to fetch fields from. Defaults to [[\craft\services\Fields::$fieldContext]].
* Set to `false` to get all fields regardless of context.
* @return FieldInterface[] The fields
* @since 4.4.0
*/
public function getFieldsByType(string $type, mixed $context = null): array
{
return ArrayHelper::where(
$this->getAllFields($context),
fn(FieldInterface $field) => $field instanceof $type,
keepKeys: false
);
}
/**
* Returns a field by its ID.
*
* @param int $fieldId The field’s ID
* @return FieldInterface|null The field, or null if it doesn’t exist
*/
public function getFieldById(int $fieldId): ?FieldInterface
{
return $this->_fields(false)->firstWhere('id', $fieldId);
}
/**
* Returns a field by its UID.
*
* @param string $fieldUid The field’s UID
* @return FieldInterface|null The field, or null if it doesn’t exist
*/
public function getFieldByUid(string $fieldUid): ?FieldInterface
{
return $this->_fields(false)->firstWhere('uid', $fieldUid, true);
}
/**
* Returns a field by its handle and optional context.
*
* ---
*
* ```php
* $body = Craft::$app->fields->getFieldByHandle('body');
* ```
* ```twig
* {% set body = craft.app.fields.getFieldByHandle('body') %}
* {{ body.instructions }}
* ```
*
* @param string $handle The field’s handle
* @param string|string[]|false|null $context The field context(s) to fetch fields from. Defaults to [[\craft\services\Fields::$fieldContext]].
* Set to `false` to get all fields regardless of context.
* @return FieldInterface|null The field, or null if it doesn’t exist
*/
public function getFieldByHandle(string $handle, mixed $context = null): ?FieldInterface
{
return $this->_fields($context)->firstWhere('handle', $handle, true);
}
/**
* Returns whether a field exists with a given handle and context.
*
* @param string $handle The field handle
* @param string|null $context The field context (defauts to [[\craft\services\Fields::$fieldContext]])
* @return bool Whether a field with that handle exists
*/
public function doesFieldWithHandleExist(string $handle, ?string $context = null): bool
{
return ArrayHelper::contains($this->getAllFields($context), 'handle', $handle, true);
}
/**
* Returns the config for the given field.
*
* @param FieldInterface $field
* @return array
* @since 3.1.0
*/
public function createFieldConfig(FieldInterface $field): array
{
return [
'name' => $field->name,
'handle' => $field->handle,
'columnSuffix' => $field->columnSuffix,
'instructions' => $field->instructions,
'searchable' => $field->searchable,
'translationMethod' => $field->translationMethod,
'translationKeyFormat' => $field->translationKeyFormat,
'type' => get_class($field),
'settings' => ProjectConfigHelper::packAssociativeArrays($field->getSettings()),
];
}
/**
* Saves a field.
*
* @param FieldInterface $field The Field to be saved
* @param bool $runValidation Whether the field should be validated
* @return bool Whether the field was saved successfully
* @throws Throwable if reasons
*/
public function saveField(FieldInterface $field, bool $runValidation = true): bool
{
if ($field instanceof MissingField) {
$error = $field->errorMessage ?? "Unable to find component class '$field->expectedType'.";
$field->addError('type', $error);
return false;
}
$isNewField = $field->getIsNew();
// Fire a 'beforeSaveField' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SAVE_FIELD)) {
$this->trigger(self::EVENT_BEFORE_SAVE_FIELD, new FieldEvent([
'field' => $field,
'isNew' => $isNewField,
]));
}
if (!$field->beforeSave($isNewField)) {
return false;
}
if ($runValidation && !$field->validate()) {
Craft::info('Field not saved due to validation error.', __METHOD__);
return false;
}
$this->prepFieldForSave($field);
$configData = $this->createFieldConfig($field);
$appliedConfig = false;
// Only store field data in the project config for global context
if ($field->context === 'global') {
$configPath = ProjectConfig::PATH_FIELDS . '.' . $field->uid;
$appliedConfig = Craft::$app->getProjectConfig()->set($configPath, $configData, "Save field “{$field->handle}”");
}
if (!$appliedConfig) {
// If it’s not a global field, or there weren't any changes in the main field settings, apply the save to the DB + call afterSave()
$this->applyFieldSave($field->uid, $configData, $field->context);
}
if ($isNewField) {
$field->id = Db::idByUid(Table::FIELDS, $field->uid);
}
return true;
}
/**
* Preps a field to be saved.
*
* @param FieldInterface $field
* @since 3.1.2
*/
public function prepFieldForSave(FieldInterface $field): void
{
// Clear the translation key format if not using a custom translation method
if ($field->translationMethod !== Field::TRANSLATION_METHOD_CUSTOM) {
$field->translationKeyFormat = null;
}
$isNew = $field->getIsNew();
// Make sure it's got a UUID
if ($isNew) {
if (empty($field->uid)) {
$field->uid = StringHelper::UUID();
}
} elseif (!$field->uid) {
$field->uid = Db::uidById(Table::FIELDS, $field->id);
}
// Store with all the populated data for future reference.
$this->_savingFields[$field->uid] = $field;
}
/**
* Handle field changes.
*
* @param ConfigEvent $event
* @throws Throwable
*/
public function handleChangedField(ConfigEvent $event): void
{
$data = $event->newValue;
$fieldUid = $event->tokenMatches[0];
if (!is_array($data)) {
return;
}
$this->applyFieldSave($fieldUid, $data, 'global');
}
/**
* Deletes a field by its ID.
*
* @param int $fieldId The field’s ID
* @return bool Whether the field was deleted successfully
*/
public function deleteFieldById(int $fieldId): bool
{
$field = $this->getFieldById($fieldId);
if (!$field) {
return false;
}
return $this->deleteField($field);
}
/**
* Deletes a field.
*
* @param FieldInterface $field The field
* @return bool Whether the field was deleted successfully
* @throws Throwable if reasons
*/
public function deleteField(FieldInterface $field): bool
{
// Fire a 'beforeDeleteField' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_DELETE_FIELD)) {
$this->trigger(self::EVENT_BEFORE_DELETE_FIELD, new FieldEvent([
'field' => $field,
]));
}
if (!$field->beforeDelete()) {
return false;
}
if ($field->context === 'global') {
Craft::$app->getProjectConfig()->remove(ProjectConfig::PATH_FIELDS . '.' . $field->uid, "Delete the “{$field->handle}” field");
} else {
$this->applyFieldDelete($field->uid);
}
return true;
}
/**
* Handle a field getting deleted.
*
* @param ConfigEvent $event
*/
public function handleDeletedField(ConfigEvent $event): void
{
$fieldUid = $event->tokenMatches[0];
$this->applyFieldDelete($fieldUid);
}
/**
* Applies a field delete to the database.
*
* @param string $fieldUid
* @throws Throwable if database error
* @since 3.1.0
*/
public function applyFieldDelete(string $fieldUid): void
{
$fieldRecord = $this->_getFieldRecord($fieldUid);
if (!$fieldRecord->id) {
return;
}
$field = $this->getFieldById($fieldRecord->id);
// Fire a 'beforeApplyFieldDelete' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_APPLY_FIELD_DELETE)) {
$this->trigger(self::EVENT_BEFORE_APPLY_FIELD_DELETE, new FieldEvent([
'field' => $field,
]));
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
$field->beforeApplyDelete();
// Soft-delete the row in `fields`
Craft::$app->getDb()->createCommand()
->softDelete(Table::FIELDS, ['id' => $fieldRecord->id])
->execute();
$field->afterDelete();
$transaction->commit();
} catch (Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Clear caches
$this->_fields = null;
// Update the field version
$this->updateFieldVersion();
// Fire an 'afterDeleteField' event
if ($this->hasEventHandlers(self::EVENT_AFTER_DELETE_FIELD)) {
$this->trigger(self::EVENT_AFTER_DELETE_FIELD, new FieldEvent([
'field' => $field,
]));
}
// Invalidate all element caches
Craft::$app->getElements()->invalidateAllCaches();
}
/**
* Refreshes the internal field cache.
*
* This should be called whenever a field is updated or deleted directly in
* the database, rather than going through this service.
*
* @since 3.0.20
*/
public function refreshFields(): void
{
$this->_fields = null;
$this->updateFieldVersion();
}
/**
* Returns all the field layouts that contain the given field.
*
* @param FieldInterface $field
* @return FieldLayout[]
* @since 5.0.0
*/
public function findFieldUsages(FieldInterface $field): array
{
if (!isset($field->id)) {
return [];
}
$layouts = [];
foreach ($this->getAllLayouts() as $layout) {
if (
ComponentHelper::validateComponentClass($layout->type, ElementInterface::class) &&
$layout->isFieldIncluded(fn(BaseField $layoutField) => (
$layoutField instanceof CustomField &&
$layoutField->getFieldUid() === $field->uid
))
) {
$layouts[] = $layout;
}
}
return $layouts;
}
/**
* @return array<int,FieldLayout[]>
*/
private function allFieldUsages(): array
{
$usages = [];
foreach ($this->getAllLayouts() as $layout) {
$uniqueFieldIds = [];
foreach ($layout->getCustomFields() as $field) {
$uniqueFieldIds[$field->id] = true;
}
foreach (array_keys($uniqueFieldIds) as $fieldId) {
$usages[$fieldId][] = $layout;
}
}
return $usages;
}
// Layouts
// -------------------------------------------------------------------------
/**
* Returns a memoizable array of all field layouts.
*
* @return MemoizableArray<FieldLayout>
*/
private function _layouts(): MemoizableArray
{
if (!isset($this->_layouts)) {
if (Craft::$app->getIsInstalled()) {
$layoutConfigs = $this->_createLayoutQuery()->all();
} else {
$layoutConfigs = [];
}
$this->_layouts = new MemoizableArray($layoutConfigs, fn(array $config) => $this->_layoutFromConfig($config));
}
return $this->_layouts;
}
private function _layoutFromConfig(array $config): FieldLayout
{
if (array_key_exists('config', $config)) {
$nestedConfig = ArrayHelper::remove($config, 'config');
if ($nestedConfig) {
$config += is_string($nestedConfig) ? JsonHelper::decode($nestedConfig) : $nestedConfig;
}
$loadTabs = false;
} else {
$loadTabs = true;
}
$layout = $this->createLayout($config);
// todo: remove after the next breakpoint
if ($loadTabs) {
$this->_legacyTabsByLayoutId($layout);
}
return $layout;
}
private function _legacyTabsByLayoutId(FieldLayout $layout): void
{
$tabQuery = (new Query())
->select([
'id',
'layoutId',
'name',
'elements',
'sortOrder',
'uid',
])
->from('{{%fieldlayouttabs}}')
->where(['layoutId' => $layout->id])
->orderBy(['sortOrder' => SORT_ASC]);
if (Craft::$app->getDb()->columnExists('{{%fieldlayouttabs}}', 'settings')) {
$tabQuery->addSelect('settings');
}
$tabResults = $tabQuery->all();
$isMysql = Craft::$app->getDb()->getIsMysql();
$tabs = [];
foreach ($tabResults as $tabResult) {
if ($isMysql) {
$tabResult['name'] = html_entity_decode($tabResult['name'], ENT_QUOTES | ENT_HTML5);
}
if (array_key_exists('settings', $tabResult)) {
$settings = ArrayHelper::remove($tabResult, 'settings');
if ($settings) {
$tabResult += JsonHelper::decode($settings);
}
}
$elements = ArrayHelper::remove($tabResult, 'elements');
if ($elements) {
$elements = JsonHelper::decode($elements);
} else {
// old school
$elements = [];
$fieldResults = (new Query())
->select(['fieldId', 'required'])
->from(['{{%fieldlayoutfields}}'])
->where(['tabId' => $tabResult['id']])
->orderBy(['sortOrder' => SORT_ASC])
->all();
foreach ($fieldResults as $fieldResult) {
$field = $this->getFieldById($fieldResult['fieldId']);
if ($field) {
$elements[] = new CustomField($field, [
'uid' => StringHelper::UUID(),
'required' => $fieldResult['required'],
]);
}
}
}
// Set the layout before anything else
$tabResult = ['layout' => $layout] + $tabResult;
$tabResult['elements'] = $elements;
$tabs[] = new FieldLayoutTab($tabResult);
}
$layout->setTabs($tabs);
}
/**