diff --git a/src/events/ApplyFieldSaveEvent.php b/src/events/ApplyFieldSaveEvent.php index 3915f1598b7..ad5d8a6eb06 100644 --- a/src/events/ApplyFieldSaveEvent.php +++ b/src/events/ApplyFieldSaveEvent.php @@ -7,14 +7,23 @@ namespace craft\events; +use craft\base\Event; +use craft\base\FieldInterface; + /** * ApplyFieldSaveEvent class. * * @author Pixel & Tonic, Inc. * @since 5.5.0 */ -class ApplyFieldSaveEvent extends FieldEvent +class ApplyFieldSaveEvent extends Event { + /** + * @var FieldInterface|null The field associated with this event, if it already exists + * in the database or in memory. + */ + public ?FieldInterface $field; + /** * @var array New field config data that is about to be applied. */ diff --git a/src/services/Fields.php b/src/services/Fields.php index 32956436afb..69e51e67b4d 100644 --- a/src/services/Fields.php +++ b/src/services/Fields.php @@ -1345,18 +1345,10 @@ public function applyFieldSave(string $fieldUid, array $data, string $context): // For control panel save requests, make sure we have all the custom data already saved on the object. if (isset($this->_savingFields[$fieldUid])) { $field = $this->_savingFields[$fieldUid]; - - if ($isNewField) { - $field->id = $fieldRecord->id; - } - } else { + } elseif (!$isNewField) { $field = $this->getFieldById($fieldRecord->id); - } - - if (!$isNewField) { - // Save the old field handle and settings on the model in case the field type needs to do something with it. - $field->oldHandle = $fieldRecord->getOldHandle(); - $field->oldSettings = is_string($oldSettings) ? Json::decode($oldSettings) : null; + } else { + $field = null; } // Fire a 'beforeApplyFieldSave' event @@ -1414,6 +1406,16 @@ public function applyFieldSave(string $fieldUid, array $data, string $context): // Tell the current CustomFieldBehavior class about the field CustomFieldBehavior::$fieldHandles[$fieldRecord->handle] = true; + if ($isNewField) { + // Try fetching the field again, if it didn’t exist to begin with + $field ??= $this->getFieldById($fieldRecord->id); + $field->id = $fieldRecord->id; + } else { + // Save the old field handle and settings on the model in case the field type needs to do something with it. + $field->oldHandle = $fieldRecord->getOldHandle(); + $field->oldSettings = is_string($oldSettings) ? Json::decode($oldSettings) : null; + } + $field->afterSave($isNewField); // Fire an 'afterSaveField' event