Magento – Return errors to form

formsvalidation

Im trying to work out how magento validates forms and returns any errors to the form page, if javascript is turned off?

Any tutorials seem to cover only the javascript side of things. So I took a look at

Mage_Customer_AccountController and Mage_Customer_Model_Customer

Mage_Customer_Model_Customer::validate() shows errors array is returned with the messages set in a helper and I see the validate function is called in Mage_Customer_AccountController::createPostAction() but what I don't understand is how I would take those error messages and apply them to the relevant input fields when they are required.

Also on line 266 I saw

$session->setEscapeMessages(true); // prevent XSS injection in user input

I know filtering user input is of paramount importance, but I thought magento did it by default, do I need to do more input validation before passing it on to the database? (so far i'm only making sure a field has a value, due to my previously mentioned assumption).

===EDIT===

After about three hours of searching for an answer and playing around with options I came up with the below code (please note: I have not put this as an answer as I am guessing its not the best way to output errors to the form).

namespace/module/indexController extends Mage_Core_Controller_Front_Action

protected function _validation($data)
{
    $errors = array();

    $valid = new Zend_Validate_NotEmpty();
    $validEmail = new Zend_Validate_EmailAddress();

    if ( !$valid->isValid( trim( $data['f_name'] )) ){
        $errors[] = Mage::getSingleton('core/session')->addError('First name must be provided');
    }

    if ( !$validEmail->isValid( $data['email'] ) ){
        $errors[] = Mage::getSingleton('core/session')->addError('Invalid email address');
    }

    return $errors;
}

public function saveAction()
{        
    if ( $this->getRequest()->getPost() ) {

        try {
        $postData = $this->getRequest()->getPost();
        $model = Mage::getModel('prefs/prefs');            
        $formData = $model->setData($postData);

        $valid = $this->_validation($formData);

        if( $valid == 0){
            if( $formData['email'] === $formData['emailAddressCheck'] ) {
                $model->load('email');
                $model->save();
                $this->_redirect('*/*/edit');                     
            } else {
                Mage::getSingleton('core/session')->addError('Emails do not match');
                $this->_redirect('*/*/signup');
            }               
        }else {
            $this->_redirect('*/*/signup');
        }

        } catch (Exception $e) {
            Mage::getSingleton('core/session')->addError($e->getMessage());
        }
    } else {
        //some error message
    }
}

Best Answer

It is better to tie the validate methods to the model. In your model you can include the validate method as follows:

public function validate() {
    $errors = array();

    if (!Zend_Validate::is($this->getFirstName(), 'NotEmpty')) {
        $errors[] = 'First name is needed';
    }

    if (!Zend_Validate::is($this->getLastName(), 'NotEmpty')) {
        $errors[] = 'Last name is needed';
    }

    if (!Zend_Validate::is($this->getDesignation(), 'NotEmpty')) {
        $errors[] = 'Designation is needed';
    }

    if (empty($errors)) {
        return true;
    }

    return $errors;
}

Then in the controller you can use it as follows:

if ($data = $this->getRequest()->getPost()) {

        $users = Mage::getModel('tableop/users')->setData($data);

        $session = Mage::getSingleton('tableop/session');

        $validate = $users->validate();         
        if ($validate === true) {

....etc

For the error and success messages part, you can use Mage::getSingleton('core/session')->addError or addSuccess methods. You can use your own session objects also.

For more information refer Mage/Review/controllers/ProductController.

Related Topic