On a Craft 3.7 site, I need to make some changes when duplicating an element:
- set the
dateCreated
,dateUpdate
&postDate
to the current date - ensure the entry is disabled
- clear the value of an asset custom field (
documentsFile
)
Theses actions should be executed when using:
- the Duplicate element action available when selecting entries in the element index
- the Save as a new entry action available in the dropdown of the Save button of an entry edit page
I tried with the following code in a module's init()
method:
Event::on(Entry::class, 'Entry::EVENT_BEFORE_SAVE', static function (ModelEvent $event) {
/** @var Entry $entry */
$entry = $event->sender;
if (
!$entry->duplicateOf
|| !$entry->sectionId
|| $entry->getSection()->handle !== 'documents'
) {
Craft::$app->getSession()->setFlash('cp-error', 'OUT');
return;
}
$now = new DateTime('now', new DateTimeZone('UTC'));
$entry->dateCreated = $now;
$entry->dateUpdated = $now;
$entry->postDate = $now;
$entry->setFieldValue('documentsFile', null);
$entry->enabled = false;
});
It works a little too well: it gets executed everytime I save a draft (and maybe even when Craft saves a provisional draft).
I'm aware of the $entry->firstSave
property and of the ElementHelper::isDraftOrRevision($entry)
method, but I'm not sure how to assemble everything to achieve what I want. The whole entry publication workflow seems really complex.
What is the reliable way to determine when an element is being duplicated?