Skip to content

Creating Custom Events

iben12 edited this page Sep 28, 2020 · 6 revisions

Requirements

  • Extension version v.1.14.0 or later
  • Creating an External Event in Emarsys (please refer to docs)

Usage

Magento's built-in event dispatcher can be used to trigger a custom external event.

use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Exception\LocalizedException;


class MyClass 
{
    /**
     * @var ManagerInterface
     */
    private $eventManager;

    public function __construct(ManagerInterface $eventManager) {
        $this->eventManager = $eventManager;
    }

    public function myTrigger() {
        $id = 123456;
        $data = [
            'customerEmail' => '[email protected]',
            'someField'     => 'someValue',
            // ...
        ];
        $storeId = 2;

        try {
            $this->eventManager->dispatch(
                'emarsys_create_custom_event',
                [
                    'event_id'   => $id,
                    'event_data' => $data,
                    'store_id'   => $storeId,
                ]
            );
        } catch(LocalizedException $e) {
            // handle the error
        }
    }
}

Parameters

event_id: This is the ID of the External Event created on Emarsys Platform. (required)

event_data: This will be the payload of the triggered event in Emarsys. It must contain a customerEmail field to identify the contact for event triggering. event_data can be either an associative array or a JSON encoded string. (required)

store_id: Defines on which Magento store view the event should be triggered on (you may have multiple stores/websites connected to Emarsys). The store_id parameter is optional, however it is strongly recommended to explicitly define it. If not defined, Observer will determine the store from the Magento context.

Errors

The observer throws LocalizedException if the event wasn't dispatched correctly.

Marketing events are not enabled for store (ID: 2): The error indicates that event triggering is not enabled for the given store view.

customerEmail is required in event_data: The error indicates the the required customerEmail field is missing from the event data object.

Need to specify data: [event_id, event_data]: The error indicates that either the event_id or the event_data parameter is missing.

Clone this wiki locally