cms
cms copied to clipboard
[4.x]: Publishing entries: validation errors are only checked for currently selected site
What happened?
Description
In a multi-site environment it is possible to publish entries that contain validation errors on sites that are not currently selected.
Steps to reproduce
- Set up two sites
- Create a section with a translatable, required field
- Create/open an entry, leave the field blank
- Switch to second site
- Enter a value for that field
- Press 'Create entry/Save'
Expected behavior
Don't publish, display errors.
Actual behavior
Gets published.
Workaround
We use a workaround in a custom module like this, but not sure whether this will or will not work under any circumstances
// Validate entries on all sites
Event::on(
Entry::class,
Entry::EVENT_BEFORE_SAVE, function($event) {
/** @var Entry $entry */
$entry = $event->sender;
// TODO: Check conditionals
if ($entry->scenario != Entry::STATUS_LIVE) {
return;
}
$entry->validate();
if ($entry->hasErrors()) {
return;
}
foreach ($entry->getLocalized()->all() as $localizedEntry) {
$localizedEntry->scenario = Entry::SCENARIO_LIVE;
if (!$localizedEntry->validate()) {
$entry->addError(
$entry->type->hasTitleField ? 'title' : 'slug',
Craft::t('site', 'Error validating entry in') .
' "' . $localizedEntry->site->name . '". ' .
implode(' ', $localizedEntry->getErrorSummary(false)));
$event->isValid = false;
}
}
});
/Aylin
Craft CMS version
4.1.2 (should be the same in Craft 3)
PHP version
8.0.15
Operating system and version
Windows 10 Pro
Database type and version
MySQL 5.7.14
Image driver and version
Imagick 3.7.0 (ImageMagick 7.1.0-18)