Add default matrix blocks when creating an entry #15638
-
We've had several clients that are asking if it is possible to have a preset of matrix blocks already created when creating a new entry page. For now we create a template entry that they can duplicate but it would be great if we could define (preferably visually in the CMS) a set of default matrix blocks that will automatically being inserted when creating an entry. Another way would be to leverage Feed me and provide a JSON or do it in a similar fashion. I reckon this should be specific on an entry type level. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Related: #14015 |
Beta Was this translation helpful? Give feedback.
-
Doing this with a field/field layout setting isn’t possible, because the default values could include relational fields, etc., which reference other content in the system. And we can’t store content references in any settings that get stored in the project config, since content varies from environment to environment. That said, you can pull it off with a little custom code in a module: <?php
use craft\base\Element;
use craft\elements\Entry;
use craft\events\ModelEvent;
use yii\base\Event;
Event::on(Entry::class, Element::EVENT_BEFORE_SAVE, function(ModelEvent $event) {
/** @var Entry $entry */
$entry = $event->sender;
if (
$event->isNew &&
$entry->getIsUnpublishedDraft() &&
$entry->section->handle === 'mySectionHandle'
) {
$entry->myMatrixFieldHandle = [
'new1' => [
'type' => 'myEntryTypeHandle',
'fields' => [
'label' => 'Label 1',
],
],
'new2' => [
'type' => 'myEntryTypeHandle',
'fields' => [
'label' => 'Label 2',
],
],
];
}
}); |
Beta Was this translation helpful? Give feedback.
Doing this with a field/field layout setting isn’t possible, because the default values could include relational fields, etc., which reference other content in the system. And we can’t store content references in any settings that get stored in the project config, since content varies from environment to environment.
That said, you can pull it off with a little custom code in a module: