Skip to content

Example (2): E-Mail notification on changes

This is just a short tutorial which shows following features:

  • Create a list of E-Mail recipients, named it watchers
  • on change or transition (Statemachine Workflow) send an email to every watcher

1. Create a property watchers in Ticket class

In our Ticket-class (Ticket.php) we add a new property named watchers which is an array of Emails:

// ...
use System\EmailProperty;
// ...
protected function getAdditionalProperties(): array
{
    return [
        // ...
        (new EmailProperty("watchers"))->asArray()
        // ...
    ];
}

OK, now we already have <input/>s in our view:

alt text

Add- and remove-buttons work out the box.

2. afterUpdate and afterChangeState hooks

We can override both functions afterUpdate() and afterChangeState(), prepare a subject and send an email:

protected function afterUpdate(): void
{
    $subject = "Update notification / {$this->subject}";
    $this->sendEmailNotificaton($subject);
}

protected function afterChangeState(?State $_from, State $_to): void
{
    $subject = "State changed / " . $this->wrap($_from->name) . " ➥ " . $this->wrap($_to->name);
    $this->sendEmailNotificaton($subject);
}

3. Finally retrieve watchers and send email

There are several ways to implement such, this is just one:

private function sendEmailNotificaton(string $email_subject, ?string $body = null)
{
    /**
     * @var EmailProperty
     */
    $watchers = $this->getProperty(("watchers"));
    $recipients = array_map(fn($w) => $w['value'], $watchers->getArrayRows());
    foreach ($recipients as $recipient) {
        Mail::send(
            $recipient,
            "",
            $email_subject ?? '',
            $body ?? (string) $this->content ?? ''
        );
    }
}

Test and results

  • Reload a Ticket-record add some Watchers
  • Make some changes and save. Your watchers will receive an email.
  • Change the state using the Statemachine Workflow. Your watchers will get another email.

alt text