0

I have two tables "first_table" and "second_table". I am using afterSave method in "first_table" model class like bellow

namespace Vendor\Module\Model;

use Magento\Framework\Model\AbstractModel;

/**
 * FirstTable model
 *
 */
class FirstTable extends AbstractModel
{
    /**
     * Model construct that should be used for object initialization
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init(\Vendor\Module\Model\ResourceModel\FirstTable::class);
    }

    /**
     * Processing object after save data
     *
     * @return $this
     */
    public function afterSave()
    {
        // some code
        parent::afterSave();
    }
}

In after save function, I want to take current record ID (By $this->getId()) and save some data in "second_table". Now what I want is if "second_table" insert goes fail, I want to revert the "first_table" insert and redirect user again to edit page. Is it possible ?

1 Answer 1

0

How about saving the second table data in the beforeSave function?

If it fails, you can throw an exception that will prevent the save first table data to happen.

Once the above is implemented, you will need a try/catch block when you call the first table save method to wrap the error message and that should allow the user to try to save the data again.

2
  • I can't have ID of first table in beforeSave() in the case of new record
    – 26vivek
    May 14, 2020 at 5:33
  • Of course, you want to use transaction. Apologies, I should have seen this anyway May 14, 2020 at 6:53

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.