Search code examples
zend-frameworkzend-formzend-form-sub-form

Splitting up a Zend_Form


I have created a Zend_From with a couple of fields. What I'd like to do, is put them inside paragraphs, so that they would flow naturally. For an example

Danny had [select with 1-10] apples and James had [select with 3-20] pears.

I have been trying to do this with

$elem= $this->registerForm->getElement('danny');

but then on the output, the value of this element is not included in the form anymore. I also thought that this could be done with Zend_Form_SubForm(), but couldn't find any examples.


Solution

  • You don't need a subform for this, just a regular form with some special decorators, or with some decorators removed.

    <?php
    
    class Your_Form_Example extends Zend_Form
    {
    
        public function init() {
            // wrap the select tag in a <span> tag, hide label, errors, and description
            $selectDecorators = array(
                'ViewHelper',
                array('HtmlTag', array('tag' => 'span'))
            );
    
            $this->addElement('select', 'danny', array(
                'required' => true,
                'multiOptions' => array('opt1', 'opt2'),
                'decorators'   => $selectDecorators // use the reduced decorators given above
            ));
        }
    }
    

    Then here is the view script that renders the form...

    <form method="<?php echo $form->getMethod() ?>" action="<?php echo $form->getAction() ?>">
      <p>Danny had <?php echo $form->danny ?> apples and James had <?php echo $form->james ?> pears.</p>
      <p>More stuff here...</p>
    
      <?php echo $form->submit ?>
    </form>
    

    This should result in something like

    <p>Danny had <span><select name="danny" id="danny"><option>opt1</option><option>opt2</option></select></span> apples and James had .....</p>
    

    To keep the form output nice, the Errors, Description, and Label decorators are removed and will not be rendered. Therefore, when you check errors on the form, you will need to display them atop the form or somewhere else if the select elements have errors since they will not be rendered along with the select elements.

    Hope that helps.