0

Building my own module and it works perfectly at the moment. My next step is to add server side validation to the data being inputted by admin in the module form.

I am validating the data in my models _beforeSave method which is fine. its wrapped in a try catch and if the validation fails it adds an error to the session.

Here is that code.

protected function _beforeSave()
{
    $data = $this->getData();
    $strLengthValidator = new Zend_Validate_StringLength();
    $strLengthValidator->setMax(40);

    try{
        $strLengthValidator->isValid($data['identifier']);
    }
    catch(Exception $e)    {
        Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
    }
}

I have 2 issues:

1) the error doesn't get saved in the session? Why is this?

2) When i eventually get the error to save in the session, how do i handle it in the controller?

Thanks

2 Answers 2

1

I am not 100% sure what is suppose to be going on here but what you should do is through a new exception in your _beforeSave function.

protected function _beforeSave()
{
    $data = $this->getData();
    $strLengthValidator = new Zend_Validate_StringLength();
    $strLengthValidator->setMax(40);

    $dataError = $strLengthValidator->isValid($data['identifier']);
    if ($dataError === false) {
        Mage::throwException(Mage::helper('core')->__('This is where you put your message');
    }
    return $this;
}

In this case what should happen is the function will throw and error, stop the saving action and then display your message to the user.

0

$strLengthValidator->isValid() return boolean, therefore it does not throw a exception so nothing to catch.

Take a look at /app/code/core/Mage/Contacts/controllers/IndexController.php

$postObject = new Varien_Object();
$postObject->setData($post);

$error = false;

if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
    $error = true;
}

...

if ($error) {
    throw new Exception();
    //or
    //Mage::throwException(Mage::helper('payment')->__('Payment action is not available.'));
}
2
  • Thanks for your help, i have got to this point now where my functions throwing an exception but the data still saves... how to i break out of the save method after i have thrown the exception? Thanks
    – Tom Burman
    Oct 17, 2014 at 15:12
  • Can you update you question with the save function and validation? Normally it best to accept and create a new question to keep thing clean since straying from the other question topic Oct 17, 2014 at 15:17

Your Answer

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

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