Custom Zend_Form view script

Sometimes Zend’s built-in form decorators are not flexible enough to achieve customized views. Luckily, Zend provides means to specify custom view scripts. The following example demonstrates how to set and handle such a script.

First and foremost, in your default (action) view script simply output the form as usual:

<div class="formContainer">
  <?php echo $this->form ?>
</div>

Then, in your derived Zend_Form class set your custom view script that takes care of rendering the form the way you need it:

/**
 * Custom Zend_Form view script example.
 * @author matthias.kerstner
 */
class Custom_Form extends Zend_Form {

    public function init() {
        $this->setDecorators(array(array(
                'viewScript',
                array(
                    'viewScript' => '_customForm.phtml',
                    array('formId' => 'CustomForm', 'formClass' => 'customForm')
            ))));

Finally, the custom Zend_Form view script looks like the following. Note that it uses additional parameters that you can specify in Custom_Form.

<?php
$params = $this->element->getDecorator('ViewScript')->getOptions();
$formId = $params[0]['formId'];
$formClass = (isset($params[0]['formClass'])) ? $params[0]['formClass'] : '';
?>

<form id="<?php echo $formId ?>" 
      class="<?php echo $formClass ?>"
      method="<?php echo $this->element->getMethod() ?>" 
      action="<?php echo $this->element->getAction() ?>" 
      enctype="<?php echo $this->element->getEnctype() ?>">

    <?php
    echo $this->element->my_element_1;
    echo $this->element->my_element_2;

    echo $this->element->submit;
    ?>

</form>

Don’t forget to call parent::init(); in any of your derived classes. Using custom view scripts gives you the full power to design your form view, but remember that in contrast to using built-in decorators you need to echo your elements manually in your view script.

You may also like...

2 Responses

  1. Brainarts says:

    Useless cause incomplete examples…
    Do the job or don’t do it halfly

    • Hello Brainarts, what further information do you need? The example presented here assumes at least some knowledge of how zend forms work. If you are more specific I’m sure we can work things out…

Leave a Reply

Your email address will not be published. Required fields are marked *

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