4

When using Craft Event triggers in PHP (e.g. Event::on), is there any event metadata that can tell where the event originated from? E.g. if it was triggered from an admin action, or if it was triggered by module code (e.g. saveElement)?

Perhaps something in the $event object?

Event::on(
  Entry::class,
    Entry::EVENT_BEFORE_SAVE,
      function(ModelEvent $event) {
        $entry = $event->sender;

Thanks!

2
  • Why do you need to know what triggered the event? It's likely you won't cover all possible scenarios if you make distinctions like that. What problem are you actually trying to solve?
    – MoritzLost
    Dec 27 '21 at 16:27
  • @MoritzLost hard to expand fully as it is a complex issue, but we were getting issues with saving matrix data via EVENT_BEFORE_SAVE, so we were considering using saveElement and EVENT_AFTER_SAVE, but, as expected, had an infinite loop of saving. Was exploring all options, including being able to tell difference between save type. However, looks like we will abandon this approach for reasons you indicate. Thanks for reply :)
    – iamkeir
    Dec 28 '21 at 20:17
3

Discovered here you can use Craft::$app->getRequest()->getIsCpRequest() to check if it was a request via control panel.

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.