For arlanix/notification 1.0.1
Customise messages
This page is for PHP developers who want more in the notifications than the modules provide, for example the city of an order, or a price formatted as money.
A rule's message is a template. The admin writes it with the event's fields, for example {order.increment_id}. When the event happens, the message is built from the event's data. Your module can change the following:
- the event's data
- the fields that a rule can use
- how a value is formatted
Choose the approach that fits your task:
| To | Do this |
|---|---|
| Format a value differently in one rule | Use a modifier in the rule's text, for example `{order.grand_total |
| Format a value differently in every rule | Change the value with an event data provider, or write a modifier. |
| Change an event's default text, or a field's label or sample | Override them in your own etc/arlanix_notification_events.xml. |
| Add a field to another module's event | Declare the field in your XML, and set its value with an event data provider. |
| Add a variable to every event | Add a {message.*} variable. |
Use a modifier
A field can take modifiers, each after a bar (|). They run from left to right. The manual lists them. For example:
{order.grand_total|currency}writes the total in the currency the default store view shows prices in, for example $129.00.{order.grand_total|currency:EUR}writes the total in euros.{customer.name|upper|truncate:20}writes the name in capitals, cut to 20 characters.
Fields that end in _formatted, such as order.grand_total_formatted, are already formatted in the order's own currency.
Change the texts and labels of an event
Magento merges the etc/arlanix_notification_events.xml files of all modules by the event's code and the field's path. So your file can change one attribute of another module's event and keep the rest.
In your etc/module.xml, add the other module to <sequence>. Magento then reads your file after the other module's file. For example, the following file changes a field's label and the subject of the sales_order_placed event:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Arlanix_Notification:etc/arlanix_notification_events.xsd">
<event code="sales_order_placed">
<field path="order.grand_total_formatted" label="Order total"/>
<subject>Order #{order.increment_id} for {order.grand_total_formatted}</subject>
</event>
</config>
The event's subject and body are used only when a rule's own subject or body is empty. A rule with its own text keeps it. Declare events lists every attribute.
Add a field to an event of another module
To add a field, follow these steps:
- Declare the field on the event in your XML.
- Write an event data provider that sets the field's value.
- Register the provider in your
etc/di.xml.
The field is then offered like the event's own fields, under Variables and in the conditions. With attribute="true", it is also shown with every message.
In step 1, declare the field on each event that needs it:
<event code="sales_order_placed">
<field path="order.city" label="City" attribute="true" sample="London"/>
</event>
<event code="sales_order_status_changed">
<field path="order.city" label="City" attribute="true" sample="London"/>
</event>
In step 2, implement EventDataProviderInterface:
<?php
declare(strict_types=1);
namespace Vendor\Module\Model\Notification;
use Arlanix\Notification\Model\Event\EventDataProviderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
class OrderCity implements EventDataProviderInterface
{
public function __construct(private readonly OrderRepositoryInterface $orders)
{
}
public function provide(string $event, array $data): array
{
$orderId = (int)($data['order']['id'] ?? 0);
if ($orderId === 0 || !str_starts_with($event, 'sales_')) {
return $data;
}
$address = $this->orders->get($orderId)->getShippingAddress();
$data['order']['city'] = (string)$address?->getCity();
return $data;
}
}
In step 3, register the provider in your etc/di.xml:
<type name="Arlanix\Notification\Model\Event\EventDataProviders">
<arguments>
<argument name="providers" xsi:type="array">
<item name="vendor_order_city" xsi:type="array">
<item name="class" xsi:type="object">Vendor\Module\Model\Notification\OrderCity</item>
<item name="sortOrder" xsi:type="number">10</item>
</item>
</argument>
</arguments>
</type>
Event data providers work as follows:
provide()receives the event's code and its data, nested as the field paths name it. It returns the data that the rules read.- A provider can also change a value. For example, if it sets
$data['order']['grand_total_formatted'], the new total appears in every rule of the event. - Providers run only when an active rule uses the event. They run once for all of the event's rules. They run after the transaction that emitted the event commits, and before any condition is checked.
- Providers run in
sortOrderorder. Each provider receives the data that the previous one returned. - If a provider throws, the error is written to
var/log/arlanix.logand the data stays as it was. The message is still sent. - Preview and Publish test message do not run providers. They use the field's
sample, so give it a realistic value.
The Events page of the manual lists the fields of each event. All order events, from sales_order_placed to sales_shipment_created, also carry the order's ID in order.id. Rules cannot use order.id, but your provider can read it.
Add a variable to every event
A {message.*} variable is available to every rule, whatever its event. {message.topic} and {message.time} are two of them. To add your own, implement Arlanix\Notification\Model\Rule\MessageVariableInterface:
<?php
declare(strict_types=1);
namespace Vendor\Module\Model\Notification;
use Arlanix\Notification\Model\Rule\MessageVariableInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
class Weekday implements MessageVariableInterface
{
public function __construct(private readonly TimezoneInterface $timezone)
{
}
public function getLabel(): string
{
return (string)__('Day of the week');
}
public function getValue(string $event, array $data): string
{
return $this->timezone->date()->format('l');
}
}
Register it in your etc/di.xml:
<type name="Arlanix\Notification\Model\Rule\MessageVariables">
<arguments>
<argument name="variables" xsi:type="array">
<item name="weekday" xsi:type="object">Vendor\Module\Model\Notification\Weekday</item>
</argument>
</arguments>
</type>
Message variables work as follows:
- The item's name is the variable's name. For example,
weekdaybecomes{message.weekday}. The name starts with a lower-case letter and contains only lower-case letters, digits and_. - The names of the built-in variables are reserved:
topic,event,source,severity,time,ruleandstore_url. Registering a variable with one of these names fails, so these names always mean the same in every rule. getValue()is called each time a rule publishes a message, and for Preview. For Preview,$dataholds the samples of the event's fields.- If
getValue()throws, the variable is empty and the error is logged. - Variables lists your variable with its label under every event. The rule form accepts it when you save the rule.
Write a modifier
A modifier is one step after a bar, for example {name|words:12}. Modifiers come from Arlanix_Core, and Arlanix Product Feed uses the same ones. So a modifier that you register is available in Arlanix Product Feed too.
The following modifier keeps the first words of a text:
<?php
declare(strict_types=1);
namespace Vendor\Module\Model\Modifier;
use Arlanix\Core\Model\Template\Modifier\Description;
use Arlanix\Core\Model\Template\Modifier\StringModifier;
class Words extends StringModifier
{
protected function transform(string $value, array $arguments): string
{
$limit = max(1, (int)($arguments[0] ?? 20));
$words = preg_split('/\s+/u', trim($value), -1, PREG_SPLIT_NO_EMPTY) ?: [];
return implode(' ', array_slice($words, 0, $limit));
}
public function describe(): Description
{
return new Description('words:20', __('Keep the first words'), 'words:12');
}
}
Register it in your etc/di.xml:
<type name="Arlanix\Core\Model\Template\ModifierPool">
<arguments>
<argument name="modifiers" xsi:type="array">
<item name="words" xsi:type="object">Vendor\Module\Model\Modifier\Words</item>
</argument>
</arguments>
</type>
Modifiers work as follows:
- Arguments arrive as strings, in the order written. For example,
words:12gives['12']. - A missing argument is not in the array, so give each argument a default. For example,
currencyuses the store view's display currency when no currency is given. - If a value has no meaning for your modifier, return it unchanged.
- If your modifier throws, the rule's message is not sent.
- If you register a modifier under the name of a core modifier, such as
currency, yours replaces it everywhere. - A rule that uses a modifier that no module registers cannot be saved.
Check it
To check your changes in the admin, follow these steps:
- Run
bin/magento setup:upgradeandbin/magento cache:clean config. - Open Arlanix > Notifications > Rules and click Add rule.
- Choose the event. Variables lists your field and your variable.
- Write them into the subject or body, and click Preview.
- Make the event happen in the store, and check the message in the Message Log.