In my opinion, the best (and simplest) approach to this problem is to use a custom validation rule to prevent authors from creating (i.e. publishing) entries using the wrong entry type at the wrong level.
Adding a custom validation rule is relatively straight-forward, but requires a (private) plugin (Craft 4.4+ only) or a custom Yii module. For this use case, a module will suffice and would be my recommendation – but assuming you're running Craft 4.3.5 or later, scaffolding either one is quite easy using the official Craft Generator package._
Here's how you could add a custom validation rule that would prevent authors from creating entryType2
entries at the root level of the structure, and entryType1
entries below the root level (this should be added to your module or plugin's init()
method:
use craft\elements\Entry;
use craft\events\DefineRulesEvent;
use yii\base\Event;
Event::on(
Entry::class,
Entry::EVENT_DEFINE_RULES,
function(DefineRulesEvent $event) {
/** @var Entry $entry */
$entry = $event->sender;
if ($entry->getSection()->handle != 'structureSectionHandle') {
return;
}
$event->rules[] = ['typeId', function () use ($entry) {
if ($entry->getType()->handle === 'entryType2' && $entry->level === 1) {
// Prevent entries with the entry type "entryType2" from being created at level 1 in the structure
$entry->addError('typeId', Craft::t('site', 'Entry type 2 entries must have a parent entry. Select a parent entry in the "Parent" field below.'));
} else if ($entry->getType()->handle === 'entryType1' && $entry->level > 1) {
// Prevent entries with the entry type "entryType1" from being created as a child entry (i.e. below level 1 in the structure
$entry->addError('typeId', Craft::t('site', 'Entry type 1 entries cannot have a parent. Remove the parent entry in the "Parent" field below.'));
}
}, 'on' => Entry::SCENARIO_LIVE];
}
);
With the above validation rule, any entryType2
entries without a parent, or entryType1
entries with a parent, will fail validation and cannot be created as a live entry (they can be saved as drafts, though).
Note: If the validation error doesn't display, make sure your Craft install is upgraded to 4.4.9 or later.