-
Notifications
You must be signed in to change notification settings - Fork 639
/
Fields.php
1500 lines (1264 loc) · 46.4 KB
/
Fields.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\services;
use Craft;
use craft\base\Field;
use craft\base\FieldInterface;
use craft\behaviors\ContentBehavior;
use craft\behaviors\ElementQueryBehavior;
use craft\db\Query;
use craft\errors\FieldGroupNotFoundException;
use craft\errors\FieldNotFoundException;
use craft\errors\MissingComponentException;
use craft\events\FieldEvent;
use craft\events\FieldGroupEvent;
use craft\events\FieldLayoutEvent;
use craft\events\RegisterComponentTypesEvent;
use craft\fields\Assets as AssetsField;
use craft\fields\Categories as CategoriesField;
use craft\fields\Checkboxes as CheckboxesField;
use craft\fields\Color as ColorField;
use craft\fields\Date as DateField;
use craft\fields\Dropdown as DropdownField;
use craft\fields\Email as EmailField;
use craft\fields\Entries as EntriesField;
use craft\fields\Lightswitch as LightswitchField;
use craft\fields\Matrix as MatrixField;
use craft\fields\MissingField;
use craft\fields\MultiSelect as MultiSelectField;
use craft\fields\Number as NumberField;
use craft\fields\PlainText as PlainTextField;
use craft\fields\RadioButtons as RadioButtonsField;
use craft\fields\Table as TableField;
use craft\fields\Tags as TagsField;
use craft\fields\Url as UrlField;
use craft\fields\Users as UsersField;
use craft\helpers\ArrayHelper;
use craft\helpers\Component as ComponentHelper;
use craft\helpers\Db;
use craft\helpers\StringHelper;
use craft\models\FieldGroup;
use craft\models\FieldLayout;
use craft\models\FieldLayoutTab;
use craft\records\Field as FieldRecord;
use craft\records\FieldGroup as FieldGroupRecord;
use craft\records\FieldLayout as FieldLayoutRecord;
use craft\records\FieldLayoutField as FieldLayoutFieldRecord;
use craft\records\FieldLayoutTab as FieldLayoutTabRecord;
use yii\base\Component;
use yii\base\Exception;
/**
* Fields service.
* An instance of the Fields service is globally accessible in Craft via [[\craft\base\ApplicationTrait::getFields()|`Craft::$app->fields`]].
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0
*/
class Fields extends Component
{
// Constants
// =========================================================================
/**
* @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://docs.craftcms.com/v3/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;
* }
* );
* ```
*/
const EVENT_REGISTER_FIELD_TYPES = 'registerFieldTypes';
/**
* @event FieldGroupEvent The event that is triggered before a field group is saved.
*/
const EVENT_BEFORE_SAVE_FIELD_GROUP = 'beforeSaveFieldGroup';
/**
* @event FieldGroupEvent The event that is triggered after a field group is saved.
*/
const EVENT_AFTER_SAVE_FIELD_GROUP = 'afterSaveFieldGroup';
/**
* @event FieldGroupEvent The event that is triggered before a field group is deleted.
*/
const EVENT_BEFORE_DELETE_FIELD_GROUP = 'beforeDeleteFieldGroup';
/**
* @event FieldGroupEvent The event that is triggered after a field group is deleted.
*/
const EVENT_AFTER_DELETE_FIELD_GROUP = 'afterDeleteFieldGroup';
/**
* @event FieldEvent The event that is triggered before a field is saved.
*/
const EVENT_BEFORE_SAVE_FIELD = 'beforeSaveField';
/**
* @event FieldEvent The event that is triggered after a field is saved.
*/
const EVENT_AFTER_SAVE_FIELD = 'afterSaveField';
/**
* @event FieldEvent The event that is triggered before a field is deleted.
*/
const EVENT_BEFORE_DELETE_FIELD = 'beforeDeleteField';
/**
* @event FieldEvent The event that is triggered after a field is deleted.
*/
const EVENT_AFTER_DELETE_FIELD = 'afterDeleteField';
/**
* @event FieldLayoutEvent The event that is triggered before a field layout is saved.
*/
const EVENT_BEFORE_SAVE_FIELD_LAYOUT = 'beforeSaveFieldLayout';
/**
* @event FieldLayoutEvent The event that is triggered after a field layout is saved.
*/
const EVENT_AFTER_SAVE_FIELD_LAYOUT = 'afterSaveFieldLayout';
/**
* @event FieldLayoutEvent The event that is triggered before a field layout is deleted.
*/
const EVENT_BEFORE_DELETE_FIELD_LAYOUT = 'beforeDeleteFieldLayout';
/**
* @event FieldLayoutEvent The event that is triggered after a field layout is deleted.
*/
const EVENT_AFTER_DELETE_FIELD_LAYOUT = 'afterDeleteFieldLayout';
// Properties
// =========================================================================
/**
* @var string
*/
public $oldFieldColumnPrefix = 'field_';
/**
* @var
*/
private $_groupsById;
/**
* @var bool
*/
private $_fetchedAllGroups = false;
/**
* @var
*/
private $_fieldRecordsById;
/**
* @var
*/
private $_fieldsById;
/**
* @var
*/
private $_allFieldHandlesByContext;
/**
* @var
*/
private $_allFieldsInContext;
/**
* @var
*/
private $_fieldsByContextAndHandle;
/**
* @var
*/
private $_fieldsWithContent;
/**
* @var
*/
private $_layoutsById;
/**
* @var
*/
private $_layoutsByType;
/**
* @var bool Whether we've already updated the field version in this request
* @see updateFieldVersion()
*/
private $_updatedFieldVersion = false;
// Public Methods
// =========================================================================
// Groups
// -------------------------------------------------------------------------
/**
* Returns all field groups.
*
* @return FieldGroup[] The field groups
*/
public function getAllGroups(): array
{
if ($this->_fetchedAllGroups) {
return array_values($this->_groupsById);
}
$this->_groupsById = [];
$results = $this->_createGroupQuery()->all();
foreach ($results as $result) {
$group = new FieldGroup($result);
$this->_groupsById[$group->id] = $group;
}
$this->_fetchedAllGroups = true;
return array_values($this->_groupsById);
}
/**
* Returns a field group by its ID.
*
* @param int $groupId The field group’s ID
* @return FieldGroup|null The field group, or null if it doesn’t exist
*/
public function getGroupById(int $groupId)
{
if ($this->_groupsById !== null && array_key_exists($groupId, $this->_groupsById)) {
return $this->_groupsById[$groupId];
}
if ($this->_fetchedAllGroups) {
return null;
}
$result = $this->_createGroupQuery()
->where(['id' => $groupId])
->one();
return $this->_groupsById[$groupId] = $result ? new FieldGroup($result) : null;
}
/**
* Saves a field group.
*
* @param FieldGroup $group The field group to be saved
* @param bool $runValidation Whether the group should be validated
* @return bool Whether the field group was saved successfully
*/
public function saveGroup(FieldGroup $group, bool $runValidation = true): bool
{
$isNewGroup = !$group->id;
// Fire a 'beforeSaveFieldGroup' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SAVE_FIELD_GROUP)) {
$this->trigger(self::EVENT_BEFORE_SAVE_FIELD_GROUP, new FieldGroupEvent([
'group' => $group,
'isNew' => $isNewGroup,
]));
}
if ($runValidation && !$group->validate()) {
Craft::info('Field group not saved due to validation error.', __METHOD__);
return false;
}
$groupRecord = $this->_getGroupRecord($group);
$groupRecord->name = $group->name;
$groupRecord->save(false);
// Now that we have an ID, save it on the model & models
if ($isNewGroup) {
$group->id = $groupRecord->id;
}
// Update our cache of it
$this->_groupsById[$group->id] = $group;
// Fire an 'afterSaveFieldGroup' event
if ($this->hasEventHandlers(self::EVENT_AFTER_SAVE_FIELD_GROUP)) {
$this->trigger(self::EVENT_AFTER_SAVE_FIELD_GROUP, new FieldGroupEvent([
'group' => $group,
'isNew' => $isNewGroup,
]));
}
return true;
}
/**
* Deletes a field group by its ID.
*
* @param int $groupId The field group’s ID
* @return bool Whether the field group was deleted successfully
*/
public function deleteGroupById(int $groupId): bool
{
$group = $this->getGroupById($groupId);
if (!$group) {
return false;
}
return $this->deleteGroup($group);
}
/**
* Deletes a field group.
*
* @param FieldGroup $group The field group
* @return bool Whether the field group was deleted successfully
*/
public function deleteGroup(FieldGroup $group): bool
{
/** @var FieldGroupRecord $groupRecord */
$groupRecord = FieldGroupRecord::find()
->where(['id' => $group->id])
->with('fields')
->one();
if (!$groupRecord) {
return false;
}
// Fire a 'beforeDeleteFieldGroup' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_DELETE_FIELD_GROUP)) {
$this->trigger(self::EVENT_BEFORE_DELETE_FIELD_GROUP, new FieldGroupEvent([
'group' => $group
]));
}
// Manually delete the fields (rather than relying on cascade deletes) so we have a chance to delete the
// content columns
/** @var Field[] $fields */
$fields = $this->getFieldsByGroupId($group->id);
foreach ($fields as $field) {
$this->deleteField($field);
}
Craft::$app->getDb()->createCommand()
->delete('{{%fieldgroups}}', ['id' => $group->id])
->execute();
// Delete our cache of it
unset($this->_groupsById[$group->id]);
// Fire an 'afterDeleteFieldGroup' event
if ($this->hasEventHandlers(self::EVENT_AFTER_DELETE_FIELD_GROUP)) {
$this->trigger(self::EVENT_AFTER_DELETE_FIELD_GROUP, new FieldGroupEvent([
'group' => $group
]));
}
return true;
}
// Fields
// -------------------------------------------------------------------------
/**
* Returns all available field type classes.
*
* @return string[] The available field type classes
*/
public function getAllFieldTypes(): array
{
$fieldTypes = [
AssetsField::class,
CategoriesField::class,
CheckboxesField::class,
ColorField::class,
DateField::class,
DropdownField::class,
EmailField::class,
EntriesField::class,
LightswitchField::class,
MatrixField::class,
MultiSelectField::class,
NumberField::class,
PlainTextField::class,
RadioButtonsField::class,
TableField::class,
TagsField::class,
UrlField::class,
UsersField::class,
];
$event = new RegisterComponentTypesEvent([
'types' => $fieldTypes
]);
$this->trigger(self::EVENT_REGISTER_FIELD_TYPES, $event);
return $event->types;
}
/**
* Returns all field types that have a column in the content table.
*
* @return string[] The field type classes
*/
public function getFieldTypesWithContent(): array
{
$fieldTypes = [];
foreach ($this->getAllFieldTypes() as $fieldType) {
/** @var Field|string $fieldType */
if ($fieldType::hasContentColumn()) {
$fieldTypes[] = $fieldType;
}
}
return $fieldTypes;
}
/**
* 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
*/
public function getCompatibleFieldTypes(FieldInterface $field, bool $includeCurrent = true): array
{
/** @var Field $field */
if (!$field::hasContentColumn()) {
return $includeCurrent ? [get_class($field)] : [];
}
// 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 = [];
$fieldColumnType = $field->getContentColumnType();
foreach ($this->getAllFieldTypes() as $class) {
if ($class === get_class($field)) {
if ($includeCurrent) {
$types[] = $class;
}
continue;
}
if (!$class::hasContentColumn()) {
continue;
}
/** @var FieldInterface $tempField */
$tempField = new $class();
if (!Db::areColumnTypesCompatible($fieldColumnType, $tempField->getContentColumnType())) {
continue;
}
$types[] = $class;
}
// Make sure the current field class is in there if it's supposed to be
if ($includeCurrent && !in_array(get_class($field), $types, true)) {
$types[] = get_class($field);
}
return $types;
}
/**
* Creates a field with a given config.
*
* @param mixed $config The field’s class name, or its config, with a `type` value and optionally a `settings` value
* @return FieldInterface The field
*/
public function createField($config): FieldInterface
{
if (is_string($config)) {
$config = ['type' => $config];
}
try {
/** @var Field $field */
$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 all fields within a field context(s).
*
* @param string|string[]|null $context The field context(s) to fetch fields from. Defaults to {@link ContentService::$fieldContext}.
* @return FieldInterface[] The fields
*/
public function getAllFields($context = null): array
{
if ($context === null) {
$context = [Craft::$app->getContent()->fieldContext];
} else if (!is_array($context)) {
$context = (array)$context;
}
$missingContexts = [];
/** @noinspection ForeachSourceInspection - FP */
foreach ($context as $c) {
if (!isset($this->_allFieldsInContext[$c])) {
$missingContexts[] = $c;
$this->_allFieldsInContext[$c] = [];
}
}
if (!empty($missingContexts)) {
$results = $this->_createFieldQuery()
->where(['fields.context' => $missingContexts])
->all();
foreach ($results as $result) {
/** @var Field $field */
$field = $this->createField($result);
$this->_allFieldsInContext[$field->context][] = $field;
$this->_fieldsById[$field->id] = $field;
$this->_fieldsByContextAndHandle[$field->context][$field->handle] = $field;
}
}
$fields = [];
/** @noinspection ForeachSourceInspection - FP */
foreach ($context as $c) {
foreach ($this->_allFieldsInContext[$c] as $field) {
$fields[] = $field;
}
}
return $fields;
}
/**
* Returns all fields that have a column in the content table.
*
* @return FieldInterface[] The fields
*/
public function getFieldsWithContent(): array
{
$context = Craft::$app->getContent()->fieldContext;
if (!isset($this->_fieldsWithContent[$context])) {
$this->_fieldsWithContent[$context] = [];
foreach ($this->getAllFields() as $field) {
if ($field::hasContentColumn()) {
$this->_fieldsWithContent[$context][] = $field;
}
}
}
return $this->_fieldsWithContent[$context];
}
/**
* 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)
{
if ($this->_fieldsById !== null && array_key_exists($fieldId, $this->_fieldsById)) {
return $this->_fieldsById[$fieldId];
}
$result = $this->_createFieldQuery()
->where(['fields.id' => $fieldId])
->one();
if (!$result) {
return $this->_fieldsById[$fieldId] = null;
}
/** @var Field $field */
$field = $this->createField($result);
$this->_fieldsById[$fieldId] = $field;
$this->_fieldsByContextAndHandle[$field->context][$field->handle] = $field;
return $field;
}
/**
* Returns a field by its handle.
*
* ---
*
* ```php
* $body = Craft::$app->fields->getFieldByHandle('body');
* ```
* ```twig
* {% set body = craft.app.fields.getFieldByHandle('body') %}
* {{ body.instructions }}
* ```
*
* @param string $handle The field’s handle
* @return FieldInterface|null The field, or null if it doesn’t exist
*/
public function getFieldByHandle(string $handle)
{
$context = Craft::$app->getContent()->fieldContext;
if (!isset($this->_fieldsByContextAndHandle[$context]) || !array_key_exists($handle, $this->_fieldsByContextAndHandle[$context])) {
// Guilty until proven innocent
$this->_fieldsByContextAndHandle[$context][$handle] = null;
if ($this->doesFieldWithHandleExist($handle, $context)) {
$result = $this->_createFieldQuery()
->where([
'fields.handle' => $handle,
'fields.context' => $context
])
->one();
if ($result) {
/** @var Field $field */
$field = $this->createField($result);
$this->_fieldsById[$field->id] = $field;
$this->_fieldsByContextAndHandle[$context][$field->handle] = $field;
}
}
}
return $this->_fieldsByContextAndHandle[$context][$handle];
}
/**
* 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 ContentService::$fieldContext)
* @return bool Whether a field with that handle exists
*/
public function doesFieldWithHandleExist(string $handle, string $context = null): bool
{
if ($context === null) {
$context = Craft::$app->getContent()->fieldContext;
}
if ($this->_allFieldHandlesByContext === null) {
$this->_allFieldHandlesByContext = [];
$results = (new Query())
->select(['handle', 'context'])
->from(['{{%fields}}'])
->all();
foreach ($results as $result) {
$this->_allFieldHandlesByContext[$result['context']][] = $result['handle'];
}
}
return (isset($this->_allFieldHandlesByContext[$context]) && in_array($handle, $this->_allFieldHandlesByContext[$context], true));
}
/**
* Returns all the fields in a given group.
*
* @param int $groupId The field group’s ID
* @return FieldInterface[] The fields
*/
public function getFieldsByGroupId(int $groupId): array
{
$results = $this->_createFieldQuery()
->where(['fields.groupId' => $groupId])
->all();
$fields = [];
foreach ($results as $result) {
$fields[] = $this->createField($result);
}
return $fields;
}
/**
* Returns all of the fields used by a given element type.
*
* @param string $elementType
* @return FieldInterface[] The fields
*/
public function getFieldsByElementType(string $elementType): array
{
$results = $this->_createFieldQuery()
->innerJoin('{{%fieldlayoutfields}} flf', '[[flf.fieldId]] = [[fields.id]]')
->innerJoin('{{%fieldlayouts}} fl', '[[fl.id]] = [[flf.layoutId]]')
->where(['fl.type' => $elementType])
->all();
$fields = [];
foreach ($results as $result) {
$fields[] = $this->createField($result);
}
return $fields;
}
/**
* 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
{
/** @var Field $field */
$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;
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
$fieldRecord = $this->_getFieldRecord($field);
// Create/alter the content table column
$contentTable = Craft::$app->getContent()->contentTable;
$oldColumnName = $this->oldFieldColumnPrefix . $fieldRecord->getOldHandle();
$newColumnName = Craft::$app->getContent()->fieldColumnPrefix . $field->handle;
if ($field::hasContentColumn()) {
$columnType = $field->getContentColumnType();
// Make sure we're working with the latest data in the case of a renamed field.
Craft::$app->getDb()->schema->refresh();
if (Craft::$app->getDb()->columnExists($contentTable, $oldColumnName)) {
Craft::$app->getDb()->createCommand()
->alterColumn($contentTable, $oldColumnName, $columnType)
->execute();
if ($oldColumnName !== $newColumnName) {
Craft::$app->getDb()->createCommand()
->renameColumn($contentTable, $oldColumnName, $newColumnName)
->execute();
}
} else if (Craft::$app->getDb()->columnExists($contentTable, $newColumnName)) {
Craft::$app->getDb()->createCommand()
->alterColumn($contentTable, $newColumnName, $columnType)
->execute();
} else {
Craft::$app->getDb()->createCommand()
->addColumn($contentTable, $newColumnName, $columnType)
->execute();
}
} else {
// Did the old field have a column we need to remove?
if (
!$isNewField &&
$fieldRecord->getOldHandle() &&
Craft::$app->getDb()->columnExists($contentTable, $oldColumnName)
) {
Craft::$app->getDb()->createCommand()
->dropColumn($contentTable, $oldColumnName)
->execute();
}
}
// Clear the translation key format if not using a custom translation method
if ($field->translationMethod !== Field::TRANSLATION_METHOD_CUSTOM) {
$field->translationKeyFormat = null;
}
$fieldRecord->groupId = $field->groupId;
$fieldRecord->name = $field->name;
$fieldRecord->handle = $field->handle;
$fieldRecord->context = $field->context;
$fieldRecord->instructions = $field->instructions;
$fieldRecord->translationMethod = $field->translationMethod;
$fieldRecord->translationKeyFormat = $field->translationKeyFormat;
$fieldRecord->type = get_class($field);
$fieldRecord->settings = $field->getSettings();
$fieldRecord->save(false);
// Now that we have a field ID, save it on the model
if ($isNewField) {
$field->id = $fieldRecord->id;
} else {
// Save the old field handle on the model in case the field type needs to do something with it.
$field->oldHandle = $fieldRecord->getOldHandle();
unset($this->_fieldsByContextAndHandle[$field->context][$field->oldHandle]);
if (
isset($this->_allFieldHandlesByContext[$field->context]) &&
$field->oldHandle != $field->handle &&
($oldHandleIndex = array_search($field->oldHandle, $this->_allFieldHandlesByContext[$field->context], true)) !== false
) {
array_splice($this->_allFieldHandlesByContext[$field->context], $oldHandleIndex, 1);
}
}
// Cache it
$this->_fieldsById[$field->id] = $field;
$this->_fieldsByContextAndHandle[$field->context][$field->handle] = $field;
if ($this->_allFieldHandlesByContext !== null) {
$this->_allFieldHandlesByContext[$field->context][] = $field->handle;
}
unset($this->_allFieldsInContext[$field->context], $this->_fieldsWithContent[$field->context]);
$field->afterSave($isNewField);
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Tell the current ContentBehavior class about the field
ContentBehavior::$fieldHandles[$field->handle] = true;
// Update the field version at the end of the request
$this->updateFieldVersion();
// Fire an 'afterSaveField' event
if ($this->hasEventHandlers(self::EVENT_AFTER_SAVE_FIELD)) {
$this->trigger(self::EVENT_AFTER_SAVE_FIELD, new FieldEvent([
'field' => $field,
'isNew' => $isNewField,
]));
}
return true;
}
/**
* 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
{
/** @var Field $field */
// 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;
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
// De we need to delete the content column?
$contentTable = Craft::$app->getContent()->contentTable;
$fieldColumnPrefix = Craft::$app->getContent()->fieldColumnPrefix;
if (Craft::$app->getDb()->columnExists($contentTable, $fieldColumnPrefix . $field->handle)) {
Craft::$app->getDb()->createCommand()
->dropColumn($contentTable, $fieldColumnPrefix . $field->handle)
->execute();
}
// Delete the row in fields
Craft::$app->getDb()->createCommand()
->delete('{{%fields}}', ['id' => $field->id])
->execute();
// Clear caches
unset(
$this->_fieldsById[$field->id],
$this->_fieldsByContextAndHandle[$field->context][$field->handle],
$this->_allFieldsInContext[$field->context],
$this->_fieldsWithContent[$field->context]
);
if (isset($this->_allFieldHandlesByContext[$field->context])) {
ArrayHelper::removeValue($this->_allFieldHandlesByContext[$field->context], $field->handle);
}
$field->afterDelete();
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Update the field version at the end of the request
$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,
]));
}
return true;
}
/**
* 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.
*/
public function refreshFields()
{
$this->_fieldRecordsById = null;
$this->_fieldsById = null;
$this->_allFieldHandlesByContext = null;
$this->_allFieldsInContext = null;
$this->_fieldsByContextAndHandle = null;
$this->_fieldsWithContent = null;
$this->updateFieldVersion();
}
// Layouts
// -------------------------------------------------------------------------
/**
* Returns a field layout by its ID.
*
* @param int $layoutId The field layout’s ID
* @return FieldLayout|null The field layout, or null if it doesn’t exist
*/
public function getLayoutById(int $layoutId)
{
if ($this->_layoutsById !== null && array_key_exists($layoutId, $this->_layoutsById)) {