My entries' titles are auto-generated from several fields values on first save.
When one of these fields values change, I would like to update the auto-generated slug also:
Event::on(
\craft\services\Elements::class,
\craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT,
function (Event $event) {
$entry = Entry::find()
->id($event->element->id)
->one();
if ([] !== $entry) {
$title = craft\helpers\StringHelper::toAscii($entry->id.'-'.$entry->title);
$title = craft\helpers\StringHelper::toLowerCase($title);
$title = str_replace(' ', '-', $title);
// 👷 I tried this below, but none works
$entry->slug = $title; // ⬅️ Not working
$entry->setFieldValue('slug', $title); // ⬅️ Error
Craft::$app->elements->saveElement($entry); // ⬅️ Infinite loop
$event->element->slug = $event->element->id; // ⬅️ Not working
}
}
);
Unfortunately, none of these methods works. Any idea how to achieve this?