cms icon indicating copy to clipboard operation
cms copied to clipboard

[4.x]: Publishing entries: validation errors are only checked for currently selected site

Open wsydney76 opened this issue 3 years ago • 0 comments

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

  1. Set up two sites
  2. Create a section with a translatable, required field
  3. Create/open an entry, leave the field blank
  4. Switch to second site
  5. Enter a value for that field
  6. 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)

Installed plugins and versions

wsydney76 avatar Jul 07 '22 14:07 wsydney76