Return a function when a field is updated

Hey there,

does anyone here have a good solution for a field (e.g. a select), which fires a function, when a certain value is selected, e.g. sending an email from another field which covers an e-mail?

Thanks in advance!

How about using a hook that checks the value of the field after it is saved rather than a field function?

Of course this could work too. And maybe it’s a lot easier for me. Do you have any suggestions or tips?

That would be something like this:

kirby()->hook('panel.page.create', function($page) {
  if($page->select field()->value() === "some_value" {
   $mailAddress = $page->email();
   // send email
  }
});

https://getkirby.com/docs/developer-guide/advanced/hooks

Edit: But I see you have already found another thread that covers a similar topic.

I see. Where can this code be placed? It needs to be fired when the page will be updated (or created) in the panel, so will it be recognized by the panel when this one will be placed in an own plug-in?

You can put the hook in your config.php or in a plugin. I think it does not make sense on page creation, but only on page update. You won’t have a value on page creation.

Ok thanks. I found this script in another post. I integrated this one – do you know, why the loading bar keeps loading and loading while updating the page?

kirby()->hook('panel.page.update', function($page) {
    $notifyfield = $page->notify()->value();
    if( $page->content()->hasField('notifyhistory') ) {
        $fieldHistory = $page->notifyhistory()->value();
    } else {
        $fieldHistory = '';
    }
    if($notifyfield !== $fieldHistory) {
      $page->update(array(
        'notifyhistory' => function($notifyfield) {
          return $notifyfield;
        }
      ));
    }
});

Could you try to disable the $page->update() function?

of course then it works. i think it runs into an infinite update process (update -> update <- update)…

That’s what I thought as well, but actually the $page->update() function should not trigger the event. It’s a panel event after all. Have to check that in the source.

Edit: I think we had that problem in the past and I thought is was fixed.

1 Like

Ok I will try this one with the new version. Thanks until now! :+1:

Works perfectly in the new kirby version. Thanks for the help!

Thanks for reporting back. Glad it works.