[4.x]: Change propagation method programmatically #16091
-
What happened?DescriptionWe would like to change the propagation method only for 1 user group (save all entries to all sites, only for this particular group). But I can't seem to write the necessary code with the EVENT_BEFORE_SAVE event. I have following code in the event hook:
Is there any way to do this programmatically? Any help greatly appreciated :) Steps to reproduce
Expected behaviorHaving the hook code working to change the propagation method only for this particular group. Actual behaviorThe entry gets saved without propagation. Craft CMS version4.12.8 PHP version8.2 Operating system and versionlinux Database type and versionmariadb Image driver and versionNo response Installed plugins and versions |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I think the only problem is the Instead, you should be checking to make sure the entry isn’t already propagating. Here’s updated code that should work. (I also simplified a couple things that didn’t need to be there.) use craft\elements\Entry;
use craft\events\ModelEvent;
use yii\base\Event;
Event::on(Entry::class, Entry::EVENT_BEFORE_SAVE, function(ModelEvent $event) {
/** @var Entry $entry */
$entry = $event->sender;
if (
!$entry->propagating &&
$entry->getSection()?->handle === 'applications' &&
Craft::$app->user->getIdentity()?->isInGroup('pm')
) {
$siteStatuses = [];
foreach (Craft::$app->sites->getAllSites() as $site) {
$siteStatuses[$site->id] = true;
}
$entry->setEnabledForSite($siteStatuses);
}
}); |
Beta Was this translation helpful? Give feedback.
I think the only problem is the
isDraftOrRevision()
check. When you first create a new entry, and when you are making edits to an entry, it’s usually going to be a draft, so this condition is preventing your code from working when it should.Instead, you should be checking to make sure the entry isn’t already propagating.
Here’s updated code that should work. (I also simplified a couple things that didn’t need to be there.)