-- bparise <[email protected]> wrote
(on Wednesday, 20 January 2010, 10:19 AM -0800):
> 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...

A better approach would be to encapsulte your "unique email address"
criteria in a validator (implementing Zend_Validate_Interface or
extending Zend_Valiate_Abstract), and attach this to the appropriate
element. This requires no overriding of methods whatsoever.


> <?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.

-- 
Matthew Weier O'Phinney
Project Lead            | [email protected]
Zend Framework          | http://framework.zend.com/
PGP key: http://framework.zend.com/zf-matthew-pgp-key.asc

Reply via email to