Is it possible to duplicate an entry as not enabled/live from the admin listing page? Just this means some user put pages live on the site that are just copies - they forget to quickly change it to disabled etc.
2 Answers
After talking with Brad in Craft support we came up with this to put in a plugin. So now when duplicate is called in the admin (list of entries) it is set to disabled. Normal Craft behaviour is to keep the same state as the entry being copied.
//if duplicate sets entry to not live / disabled
Event::on(
Entry::class,
Entry::EVENT_BEFORE_SAVE,
function(ModelEvent $event) {
$entry = $event->sender;
// If the Entry is being duplicated.
if ($entry->duplicateOf) {
$entry->enabled = false;//set to disabled
}
});
Using duplicateOf
is not sufficient to detect duplicates. A draft, provisional draft or revision being applied to the live entry will also have a duplicateOf
property, so this will result in live entries being disabled on save (see this issue on Github for reference).
To be sure the hook only applies to duplicated entries, you also need to check the updatingFromDerivative
property – if that is false, the entry is being duplicated.
Here's a complete working hook for Craft 3.7:
use craft\elements\Entry;
use craft\events\ModelEvent;
use craft\helpers\ElementHelper;
Event::on(
Entry::class,
Entry::EVENT_BEFORE_SAVE,
function (ModelEvent $e) {
$entry = $e->sender;
if (ElementHelper::isDraftOrRevision($entry)) return;
if (!$entry->duplicateOf || $entry->updatingFromDerivative) return;
$entry->enabled = false;
}
);
In Craft 4, duplicated entries will be disabled by default (see the discussion on Github for reference).