1

I want to send a Mail to an admin, whenever a User of group ‚Cook‘ creates an Entry of Type ‚Recipe‘.

For that I created an Event reacting on Entry::EVENT_AFTER_SAVE :

Event::on(
    Entry::class,
    Entry::EVENT_AFTER_SAVE, static function (ModelEvent $event) {

    /** Entry @entry */
    $entry = $event->sender;

    /** @var User $user */
    $user = Craft::$app->getUser();

    if (!$event->isNew) {
        if ($user->identity->isInGroup('cook') &&
            ElementHelper::isDraftOrRevision($entry) &&
            $entry->getStatus() === Entry::STATUS_DISABLED) {

         
            $cpUrl = $entry->cpEditUrl;
            $bodyText = "Dear Admin. /n $userName has created <a href=$cpUrl>$entry</a>.";
        

        };
    }
});

As your can see - I tried a lot to only react on the first creation of the entry. But all this does not the trick. Behind the scenes craft created an Entry (and saves it initially) even when the Cook presses the ’New Entry’ Button.

So I don’t know hook in only when the message is first saved directly by the user pressing the ‚Create‘ Button after entering the content.

It would be nice if your could help me with that.

Thanks in advance. Michael

2
  • You only want this to fire on new entries? – RitterKnight Jan 25 at 2:19
  • Yes - the admin just wants to have one email, when the user saved a new recipe first time. – Slowwie Jan 25 at 3:37
2

Your code is pretty close. You want to make sure it's a new entry and not a draft or a revision so you could use:

Event::on(
    Entry::class,
    Entry::EVENT_AFTER_SAVE, static function (ModelEvent $event) {

    /** Entry @entry */
    $entry = $event->sender;

    /** @var User $user */
    $user = Craft::$app->getUser();

    if (
        $event->isNew // Makes sure it's a new entry
        $user->identity->isInGroup('cook') && // Makes sure your user is in the cook group
        !ElementHelper::isDraftOrRevision($entry) && // Makes it's not a draft or a revision
    ) {  
            $cpUrl = $entry->cpEditUrl;
            $bodyText = "Dear Admin. /n $userName has created <a href=$cpUrl>$entry</a>.";
    }
});
2
  • Ok, that don't work - because the 'cook' can only save drafts - not publish. – Slowwie Jan 25 at 15:47
  • Anyway - I found a solution. When I test $request->isPost then it works. the initial save event is a get request to the edit site. Maybe I have to add a conditional for not allow ajax calls and only react on the first post request. – Slowwie Jan 25 at 15:50

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.