How to saveElement in EVENT_AFTER_SAVE_ELEMENT without infinite loop 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-&gt;element instanceof \craft\elements\Entry) {
        if ($element-&gt;section-&gt;id == 1 &amp;&amp; $element-&gt;typeId == 1) {
            $element = $event-&gt;element;
            $newTitle = "new title"; // logic goes here
            $element-&gt;title = $newTitle;
            Craft::$app-&gt;elements-&gt;saveElement($element); // causes loop
        }
    }
});


Is there a way to do this? Thanks.
I got this working by using the EVENT_BEFORE_SAVE_ELEMENT and adding the asset to the entry asset field 'pdfThumbnailImage' by using the setFieldValue.

 $entry-&gt;setFieldValue('pdfThumbnailImage', [$assetId]);


You dont need to save the element - leave this out

 Craft::$app-&gt;elements-&gt;saveElement($element); // causes loop