4

I want to add aftersave and beforesave method of Magento 2 in my model.

How can I do this and which model I have to called ?

2 Answers 2

5

you can used _beforeSave and _afterSave in your ResourceModel

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

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

        }

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



    }
6
  • If I put logic to save data in _aftersave() function then what will be the use of $object ? I means, Is it compulsory to use $object or save in $object in my logic ? (for ex. $object->setName(''Test")->save(); or $mymodel->setName("Test")->save() )
    – Krupali
    Jun 7, 2016 at 10:27
  • $object->getData('identifier') Jun 7, 2016 at 10:29
  • Sorry.But what do you mean by "identifier" and is it not possible to use in Namespace/Modulname/Model/Test.php ?
    – Krupali
    Jun 7, 2016 at 10:37
  • this is your field name identifier change as your field name Jun 7, 2016 at 10:46
  • ok and as I asked is it not possible to use in Namespace/Modulname/Model/Test.php ? If i extend this Test.php file with Magento\Framework\Model\AbstractModel . Then ?
    – Krupali
    Jun 7, 2016 at 10:49
0

you can use tag to rewrite the model you want

1
  • Hi, thank you for your answer! The best answers include a bit of an example, maybe some code, to show how it's done. Oct 26, 2020 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.