Magento has a very powerful event observer system. It provides events for almost all actions. What’s great is that it can even provide event observers for your custom models. And that too without writing extra code for defining the event observers. For example you may want to perform an action when your custom model is saved in the database. You can easily catch the model save event and perform the necessary action. There is a generic Event in Magento that is triggered when any of the model in Magento is saved. These events are
model_save_after
model_save_commit_after
model_save_before
If you want to take a look at how these events are dispatched, you can find them out in File: vendor/magento/framework/Model/AbstractModel.php
Magento also extends this functionality to the custom models. So Magento triggers all the above events for your custom models also. The events will look like:
<eventPrefix>_save_after
<eventPrefix>_save_commit_after
<eventPrefix>_save_before
In your Model definition class you have to provide the event prefix as below:
<?php namespace Webspeaks\MyModule\Model; use Magento\Framework\DataObject\IdentityInterface; class MyModel extends \Magento\Framework\Model\AbstractModel implements IdentityInterface { /** * Prefix of model events names. * * @var string */ protected $_eventPrefix = 'my_model'; ... }
Now to catch the model related events we will specify them in our module’s etc/events.xml
.
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <!-- Define observer for our custom model save event --> <event name="my_model_save_after"> <observer name="my_model_save_after_event" instance="Webspeaks\MyModule\Observer\CustomSaveAfter" /> </event> </config>
Note that we declared the event prefix in our model class as my_model
. So the event name becomes my_model
+ _save_after
= my_model_save_after
.
Now we will create the observer class in Webspeaks/MyModule/Observer/CustomSaveAfter.php
.
<?php namespace Webspeaks\MyModule\Observer; use Magento\Framework\Event\ObserverInterface; class CustomSaveAfter implements ObserverInterface { public function execute(\Magento\Framework\Event\Observer $observer) { try { // Get the model object from observer $model = $observer->getEvent()->getDataObject(); if ($model && $model->isObjectNew()) { // perform some action if new model } else { // perform some action if edit model } } catch (\Exception $e) { } } }
You can also check if the model is new or old. If it is being saved first time the isObjectNew()
method will return true.
One thought on “Magento 2: Event Observer for Custom Model Save”