:::: MENU ::::

Magento 2 after save and before save method

Magento 2 after save and before save method

This tutorial is about Magento 2 after save and before save method .i.e how to use after save and before save methods in magento 2.I assume you want to add after save and before save method of Magento 2 in your model.So, how can we do this?. This tutorial will tell us,how we can do that?

Magento is a flexible platform and it covers almost all the basic and necessary functionalities. Magento has its own _beforeSave and _afterSave functions. You can use them in your ResourceModel using below code.

Before Save

_beforeSave function called when you tried to update or insert data in database table with your model. Then _beforeSave function is called. You can implement you logic like validation, Post data change or any other functionality you want perform.

<?php
    namespace QaisarSatti\HelloWorld\Model\ResourceModel;
    class Test extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb  {

        protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
        {
            // do your logic here

        }

 

    }

After Save

_afterSave function called when After update or insert data in database table with your model. Then _afterSave function is called. You can implement you logic like sending email, Add related data or any other functionality you want perform.

<?php
    namespace QaisarSatti\HelloWorld\Model\ResourceModel;
    class Test extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb  {

       protected function _afterSave(\Magento\Framework\Model\AbstractModel $object)
        {  
          //do your logic here
        }

    }

That’s it from this tutorial. I hope it serves the purpose.
Since these are learning tutorials,please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: November 9, 2018


So, what do you think ?