PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Sub Forms

Sub forms serve several purposes:

  • Creating logical element groups. Since sub forms are simply forms, you can validate subforms as individual entities.

  • Creating multi-page forms. Since sub forms are simply forms, you can display a separate sub form per page, building up multi-page forms where each form has its own validation logic. Only once all sub forms validate would the form be considered complete.

  • Display groupings. Like display groups, sub forms, when rendered as part of a larger form, can be used to group elements. Be aware, however, that the master form object will have no awareness of the elements in sub forms.

A sub form may be a Zend_Form object, or, more typically, a Zend_Form_SubForm object. The latter contains decorators suitable for inclusion in a larger form (i.e., it does not render additional HTML form tags, but does group elements). To attach a sub form, simply add it to the form and give it a name:

<?php
$form
->addSubForm($subForm'subform');

You can retrieve a sub form using either getSubForm($name) or overloading using the sub form name:

<?php
// Using getSubForm():
$subForm $form->getSubForm('subform');

// Using overloading:
$subForm $form->subform;

Sub forms are included in form iteration, although the elements they contain are not.

Global Operations

Like elements and display groups, there are some operations that might need to affect all sub forms. Unlike display groups and elements, however, sub forms inherit most functionality from the master form object, and the only real operation that may need to be performed globally is setting decorators for sub forms. For this purpose, there is the setSubFormDecorators() method. In the next example, we'll set the decorator for all subforms to be simply a fieldset (the FormElements decorator is needed to ensure its elements are iterated):

<?php
$form
->setSubFormDecorators(array(
    
'FormElements',
    
'Fieldset'
));

Methods for Interacting With Sub Forms

The following methods may be used to interact with sub forms:

  • addSubForm(Zend_Form $form, $name, $order = null)

  • addSubForms(array $subForms)

  • setSubForms(array $subForms)

  • getSubForm($name)

  • getSubForms()

  • removeSubForm($name)

  • clearSubForms()

  • setSubFormDecorators(array $decorators)

Zend Framework