1

I have the following codes inside a custom resourceModel class:

protected function _beforeSave(
    AbstractModel $object
)
{
    //My operations
    return parent::_beforeSave($object);
}

I added a checking inside _beforeSave() but I don't know how to prevent the resuorce model to continue the save actions.

I found this answer but it's for M1. I need a M2 solution.

Cancel save() in custom model if condition is met in _beforeSave()

2
  • You can do the same in M2 just set $this->_dataSaveAllowed = false; if your condition does not satisy
    – Keyur Shah
    Jan 4, 2018 at 10:22
  • Not working, the save action continue in my case.
    – PY Yick
    Jan 4, 2018 at 10:52

1 Answer 1

3

Just throw exception.

protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
    {

     if(!$object->getData('identifier')):
         throw new \Magento\Framework\Exception\LocalizedException(
                __('The page URL key not set.')
            );
     endif;
        return parent::_beforeSave($object);

}
3
  • My bad. Actually I want sth like Magento\Framework\Message\ManagerInterface::addErrorMessage(__('The page URL key not set.'));. Your method will throw an error page like PHP error.
    – PY Yick
    Jan 4, 2018 at 10:51
  • @PYYick this is used magento 2 default ResourceModel you can check it Magento\Cms\Model\ResourceModel\Block.php Jan 4, 2018 at 11:32
  • I don't know why in my case, when throw exceptions, will generate a page like PHP syntax error. While in Magento_Cms it shows error message like the one I want.
    – PY Yick
    Jan 5, 2018 at 2:37

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.