3

I have a custom model and I want to add a validation in the _beforeSave() method so that if it's a new object, and no customer_id has been set, it shouldn't save the record at all. I did the validations on my pages but that doesn't keep other developers from doing something like:

$myModel = Mage::getModel("myModule/myModel");
$myModel->save();

This shouldn't happen because some values must be set before saving. I want something like:

public function _beforeSave()
{
    parent::_beforeSave();
    if($this->getCustomerId() <= 0)
    {
         #cancel save
    }

    return $this;
}

Can I cancel the save() method?

0

1 Answer 1

3

hi need to throw a magento exception when match you logic

or set variable $_dataSaveAllowed=true

and set if false when before logic is match with cancel condition

$this->_dataSaveAllowed=false;

and note that you need call parent::_beforesave() after condition check

protected function _beforeSave()
    {
        $this->_dataSaveAllowed = true;

    if($this->getCustomerId() <= 0)
        {
         #cancel save
          $this->_dataSaveAllowed = false;
        }

    return parent::_beforeSave();
    }

Just like

 throw Mage::exception(
                'Mage_Customer', Mage::helper('customer')->__('This customer email already exists'),
                Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS
            );

See some brief description

How prevent a model data save using _save_before event

1
  • Hey, thanks man. I thought about throwing an exception but I went with $_dataSaveAllowed=false. This model isn't exactly an important one and I did not want to throw a nasty exception. You can go ahead and mark this question as a duplicate though, I did not find yours first.
    – Vic
    Commented Oct 3, 2014 at 17:54

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