How do you effectively override the Zend_Form::isValid() method?
Our usage, we have a EditProfileForm that requires a unique email address. 
Since there are no real built-in validators to handle this, we decided to
simply override the Zend_Form::isValid() and manually set the email field as
an error...

<?php
class EditProfileForm extends AppForm // extends Zend_Form
{
    public function isValid($data)
    {
        parent::isValid($data);

        if (!$this->getElement('email')->hasErrors()) {
            $u =
Doctrine_Core::getTable('User')->findOneByEmail($this->getValue('email'));
            if (!empty($u) && ($u->id !== $this->getModel()->id)) {
                $this->getElement('email')->addError(sprintf('The email
\'%s\' is already registered by another user.', $this->getValue('email')));
            }
        }

        return ($this->isErrors() === false);

    }
}
?>

But, this doesn't work. Zend_Form::isErrors() doesn't dynamically loop
through elements to get errors (which means the form doesn't get
notification of us adding an error the 'email' element).  Plus, if you call
parent::isValid($data) after we set the email error, they are reset since
Element::isValid() resets the errors.

So, again, what is the best way to handle this situation?

We came up with the solution of...

<?php
class EditProfileForm extends AppForm // extends Zend_Form
{
    public function isValid($data)
    {
        $isValid = parent::isValid($data);
        
        // Try e-mail.
        if (!$this->getElement('email')->hasErrors()) {
            $u =
Doctrine_Core::getTable('User')->findOneByEmail($this->getValue('email'));
            if (!empty($u) && ($u->id !== $this->getModel()->id)) {
                $this->getElement('email')->addError(sprintf('The email
\'%s\' is already registered by another user.', $this->getValue('email')));
                $isValid = false;
            }
        }
                
        return $isValid;
    }
}
?>

Which works as expected, but wanted to see if there was a better way to do
this.
Thanks!
    


-- 
View this message in context: 
http://n4.nabble.com/Overriding-Zend-Form-isValid-tp1018622p1018622.html
Sent from the Zend Framework mailing list archive at Nabble.com.

Reply via email to