2

I am trying to get the value of a custom field in entries, but I can't seem to get it to grab that value. I'm assuming I'm pulling it too early or too late, otherwise I have no idea.

I can pull the value the of the lightswitch enabled

Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) 
    {
        $request = Craft::$app->getRequest();

        // will successfully send email if enabled lightswitch is on
        if($request->getBodyParam('enabled') == 1)
        {
            $html = $request->getBodyParam('enabled');
            $subject = "testing";
            $mail = "example@gmail.com";
            return $this->sendMail($html, $subject, $mail);
        }
    });

The below doesn't return anything at all for the custom field fields[sendEmail]

Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) 
    {
        $request = Craft::$app->getRequest();

        // will not send email no matter what position the lightswitch is in
        if($request->getBodyParam('fields[sendEmail]') == 1)
        {
            $html = $request->getBodyParam('fields[sendEmail]');
            $subject = "testing";
            $mail = "example@gmail.com";
            return $this->sendMail($html, $subject, $mail);
        }
    });

I tried changing the event handler to EVENT_BEFORE_SAVE_ELEMENT but it made no difference.

2

Found my answer here

// get $_POST['foo']['bar'], if it exists
$bar = Craft::$app->request->getBodyParam('foo.bar');

or inserting it into my code

Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) 
{
    $request = Craft::$app->getRequest();

    if($request->getBodyParam('fields.sendEmail') == 1)
    {
        $html = $request->getBodyParam('fields.sendEmail');
        $subject = "testing";
        $mail = "example@gmail.com";
        $this->sendMail($html, $subject, $mail);
    }
});
  • If someone wants to expand on this I'd be happy to select someone else's contribution as top answer, such as a possible better way of doing this. – Darryl Hardin Dec 19 '18 at 18:31
  • Just occurred to me my answer above isn't complete. While it did accomplish what I asked, EVENT_AFTER_SAVE_ELEMENT is for any element being saved, which means I have to find a way to determine what element is being saved. – Darryl Hardin Dec 19 '18 at 19:53

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.