Custom Zend Form rendering using view scripts

There are times when the ordinary decorators just is not enough for your forms. I had one project where we used clickable images to affect the contents of our form element. These images needed to be embedded into the form. Doing this with decorators turned out to be complicated so we used custom view scripts instead. It gave much more readable code.

Here is a small example in Zend Framework 1.10

First we need a form (application/forms/Login.php):

class Application_Form_Login extends Zend_Form {

    public function init() {

        $this->setName('login');

        $email = new Zend_Form_Element_Text('email');
        $email->addValidator('EmailAddress')
                ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim');

        $pass = new Zend_Form_Element_Password('pass');
        $pass ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim');

        $submit = new Zend_Form_Element_Submit('login');
        $submit->setLabel('Login');      

        $this->addElements(array($email, $pass, $submit));
    }
}

Then we create the view script (application/views/scripts/index/loginForm.phtml):

Login/E-mail: element->email ?>
Password: <?php echo $this->element->pass ?>
<?php echo $this->element->login ?>

And finally we link them together. First we set the the path to the view script in the form (application/forms/Login.php). I do this because I do not want to put it in the default location (application/view/scripts)

...
$this->setDecorators(array(
      array('viewScript', array('viewScript' => 'index/loginForm.phtml'))
      ));
...

Then we tell the elements that they are going to use the script when rendering (application/forms/Login.php)

...
$email->addValidator('EmailAddress')
           ->setDecorators(array('ViewHelper'))
           ->setRequired(true)
...
...
$pass ->setRequired(true)
          ->setDecorators(array('ViewHelper'))
          ->addFilter('StripTags')
...

That’s it!

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.