I am trying to update an entry's title in a Craft 3 module after an entry is saved. I cannot use EVENT_BEFORE_SAVE_ELEMENT because the title gets updated after this. If I use EVENT_AFTER_SAVE_ELEMENT to update the title and then do saveElement
the event gets called again and I get into an infinite loop.
Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) {
if ($event->element instanceof \craft\elements\Entry) {
if ($element->section->id == 1 && $element->typeId == 1) {
$element = $event->element;
$newTitle = "new title"; // logic goes here
$element->title = $newTitle;
Craft::$app->elements->saveElement($element); // causes loop
}
}
});
Is there a way to do this? Thanks.