2

In my plugin I am registering a callback for Elements::EVENT_AFTER_SAVE_ELEMENT event. Previously, in Craft2, I could access the URL of the saved entry from the $event parameter passed into the callback, like so: $event->params['entry']->getUrl().

However I can't figure out how to get a reference to the entry in the Event model in Craft 3. If I var_dump($event) I can see the data I want nested deep inside a private property which I cannot access.

How do I access the entry data from the event in Craft 3?

3

Check out the definition of the ElementEvent that you're passed:

class ElementEvent extends Event
{
    // Properties
    // =========================================================================

    /**
     * @var ElementInterface|null The element model associated with the event.
     */
    public $element;

    /**
     * @var bool Whether the element is brand new
     */
    public $isNew = false;
}

So you can access the element (in your case, presumably an Entry) via:

$event->element

Make sure to check for null, and depending on how you set up the event listener, that the element is of the type of you're looking for.

For instance, if you want only listen to all elements that are saved, you'd do:

    Event::on(
        Elements::class,
        Elements::EVENT_AFTER_SAVE_ELEMENT,
        function (ElementEvent $event) {
            Craft::debug(
                'Elements::EVENT_AFTER_SAVE_ELEMENT',
                __METHOD__
            );
        }
    );

...but if you only care about Entry elements, you'd do:

    Event::on(
        Entry::class,
        Entry::EVENT_AFTER_SAVE,
        function (ModelEvent $event) {
            Craft::debug(
                'Entry::EVENT_AFTER_SAVE',
                __METHOD__
            );
        }
    );
| improve this answer | |
  • Ah it seems I have much to learn about Craft's new event model. I think my callback was getting called multiple times and the first time I just happened to be looking at a matrix. I tried your code with Entry::class instead of Elements::class but the callback never gets called. Is there something obvious I might be missing? – Jameal G Jul 6 '18 at 19:41
  • Ended up getting it working with this: Event::on(Entry::class, Entry::EVENT_AFTER_SAVE, function (Event $event) {}); – Jameal G Jul 6 '18 at 19:51
  • My bad, copy and paste error, I fixed the original answer – andrew.welch Jul 7 '18 at 16:40

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.