2

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.

1
  • Yes how do you do this? Seems a lack of documentation or examples for events and plugins
    – joomkit
    Jul 3, 2018 at 16:05

1 Answer 1

3

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->setFieldValue('pdfThumbnailImage', [$assetId]);

You dont need to save the element - leave this out

 Craft::$app->elements->saveElement($element); // causes loop
6
  • Thank you, but this doesn't work for the title field. Custom fields can be updated like this using EVENT_BEFORE_SAVE_ELEMENT, but the title gets changed again after this.
    – Arthur
    Jul 4, 2018 at 15:38
  • Are you using setFieldValue('title') ? What about something like : if(isset($fields['title'])) { $entry->title = $fields['title']; unset($fields['title']); } if(isset($fields['slug'])) { $entry->slug = $fields['slug']; unset($fields['slug']); } $entry->setFieldValues($fields); via -> craftcms.stackexchange.com/questions/20962/…
    – joomkit
    Jul 4, 2018 at 15:50
  • $element->setFieldValue('title') is an Unknown Property, and setting $element->title doesn't work as it gets overwritten after the event.
    – Arthur
    Jul 4, 2018 at 16:08
  • Just tested in my plugin : $entry->title = "Fooobar"; worked fine when saving in the CP. That's without Craft::$app->elements->saveElement($element); Maybe check you are not saving the element and use the event EVENT_BEFORE_SAVE_ELEMENT. Just setting the title $entry->title = 'whatever'
    – joomkit
    Jul 4, 2018 at 16:44
  • Ah, it wasn't working for me because I had Show the Title field disabled with a temporary name in the Title Format field. That was overwriting my code. When I turn Show the Title field back on the $entry->title = "Fooobar" works. Thank you so much for your help. :)
    – Arthur
    Jul 4, 2018 at 17:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.