Internationalization of Zend_Form

Advanced Zend_Form Usage

Zend_Form has a wealth of functionality, much of it aimed at experienced developers. This chapter aims to document some of this functionality with examples and use cases.

Array Notation

Many experienced web developers like to group related form elements using array notation in the element names. For example, if you have two addresses you wish to capture, a shipping and a billing address, you may have identical elements; by grouping them in an array, you can ensure they are captured separately. Take the following form, for example:

  1. <form>
  2.     <fieldset>
  3.         <legend>Shipping Address</legend>
  4.         <dl>
  5.             <dt><label for="recipient">Ship to:</label></dt>
  6.             <dd><input name="recipient" type="text" value="" /></dd>
  7.  
  8.             <dt><label for="address">Address:</label></dt>
  9.             <dd><input name="address" type="text" value="" /></dd>
  10.  
  11.             <dt><label for="municipality">City:</label></dt>
  12.             <dd><input name="municipality" type="text" value="" /></dd>
  13.  
  14.             <dt><label for="province">State:</label></dt>
  15.             <dd><input name="province" type="text" value="" /></dd>
  16.  
  17.             <dt><label for="postal">Postal Code:</label></dt>
  18.             <dd><input name="postal" type="text" value="" /></dd>
  19.         </dl>
  20.     </fieldset>
  21.  
  22.     <fieldset>
  23.         <legend>Billing Address</legend>
  24.         <dl>
  25.             <dt><label for="payer">Bill To:</label></dt>
  26.             <dd><input name="payer" type="text" value="" /></dd>
  27.  
  28.             <dt><label for="address">Address:</label></dt>
  29.             <dd><input name="address" type="text" value="" /></dd>
  30.  
  31.             <dt><label for="municipality">City:</label></dt>
  32.             <dd><input name="municipality" type="text" value="" /></dd>
  33.  
  34.             <dt><label for="province">State:</label></dt>
  35.             <dd><input name="province" type="text" value="" /></dd>
  36.  
  37.             <dt><label for="postal">Postal Code:</label></dt>
  38.             <dd><input name="postal" type="text" value="" /></dd>
  39.         </dl>
  40.     </fieldset>
  41.  
  42.     <dl>
  43.         <dt><label for="terms">I agree to the Terms of Service</label></dt>
  44.         <dd><input name="terms" type="checkbox" value="" /></dd>
  45.  
  46.         <dt></dt>
  47.         <dd><input name="save" type="submit" value="Save" /></dd>
  48.     </dl>
  49. </form>

In this example, the billing and shipping address contain some identical fields, which means one would overwrite the other. We can solve this solution using array notation:

  1. <form>
  2.     <fieldset>
  3.         <legend>Shipping Address</legend>
  4.         <dl>
  5.             <dt><label for="shipping-recipient">Ship to:</label></dt>
  6.             <dd><input name="shipping[recipient]" id="shipping-recipient"
  7.                 type="text" value="" /></dd>
  8.  
  9.             <dt><label for="shipping-address">Address:</label></dt>
  10.             <dd><input name="shipping[address]" id="shipping-address"
  11.                 type="text" value="" /></dd>
  12.  
  13.             <dt><label for="shipping-municipality">City:</label></dt>
  14.             <dd><input name="shipping[municipality]" id="shipping-municipality"
  15.                 type="text" value="" /></dd>
  16.  
  17.             <dt><label for="shipping-province">State:</label></dt>
  18.             <dd><input name="shipping[province]" id="shipping-province"
  19.                 type="text" value="" /></dd>
  20.  
  21.             <dt><label for="shipping-postal">Postal Code:</label></dt>
  22.             <dd><input name="shipping[postal]" id="shipping-postal"
  23.                 type="text" value="" /></dd>
  24.         </dl>
  25.     </fieldset>
  26.  
  27.     <fieldset>
  28.         <legend>Billing Address</legend>
  29.         <dl>
  30.             <dt><label for="billing-payer">Bill To:</label></dt>
  31.             <dd><input name="billing[payer]" id="billing-payer"
  32.                 type="text" value="" /></dd>
  33.  
  34.             <dt><label for="billing-address">Address:</label></dt>
  35.             <dd><input name="billing[address]" id="billing-address"
  36.                 type="text" value="" /></dd>
  37.  
  38.             <dt><label for="billing-municipality">City:</label></dt>
  39.             <dd><input name="billing[municipality]" id="billing-municipality"
  40.                 type="text" value="" /></dd>
  41.  
  42.             <dt><label for="billing-province">State:</label></dt>
  43.             <dd><input name="billing[province]" id="billing-province"
  44.                 type="text" value="" /></dd>
  45.  
  46.             <dt><label for="billing-postal">Postal Code:</label></dt>
  47.             <dd><input name="billing[postal]" id="billing-postal"
  48.                 type="text" value="" /></dd>
  49.         </dl>
  50.     </fieldset>
  51.  
  52.     <dl>
  53.         <dt><label for="terms">I agree to the Terms of Service</label></dt>
  54.         <dd><input name="terms" type="checkbox" value="" /></dd>
  55.  
  56.         <dt></dt>
  57.         <dd><input name="save" type="submit" value="Save" /></dd>
  58.     </dl>
  59. </form>

In the above sample, we now get separate addresses. In the submitted form, we'll now have three elements, the 'save' element for the submit, and then two arrays, 'shipping' and 'billing', each with keys for their various elements.

Zend_Form attempts to automate this process with its sub forms. By default, sub forms render using the array notation as shown in the previous HTML form listing, complete with ids. The array name is based on the sub form name, with the keys based on the elements contained in the sub form. Sub forms may be nested arbitrarily deep, and this will create nested arrays to reflect the structure. Additionally, the various validation routines in Zend_Form honor the array structure, ensuring that your form validates correctly, no matter how arbitrarily deep you nest your sub forms. You need do nothing to benefit from this; this behaviour is enabled by default.

Additionally, there are facilities that allow you to turn on array notation conditionally, as well as specify the specific array to which an element or collection belongs:

  • Zend_Form::setIsArray($flag): By setting the flag TRUE, you can indicate that an entire form should be treated as an array. By default, the form's name will be used as the name of the array, unless setElementsBelongTo() has been called. If the form has no specified name, or if setElementsBelongTo() has not been set, this flag will be ignored (as there is no array name to which the elements may belong).

    You may determine if a form is being treated as an array using the isArray() accessor.

  • Zend_Form::setElementsBelongTo($array): Using this method, you can specify the name of an array to which all elements of the form belong. You can determine the name using the getElementsBelongTo() accessor.

Additionally, on the element level, you can specify individual elements may belong to particular arrays using Zend_Form_Element::setBelongsTo() method. To discover what this value is -- whether set explicitly or implicitly via the form -- you may use the getBelongsTo() accessor.

Multi-Page Forms

Currently, Multi-Page forms are not officially supported in Zend_Form; however, most support for implementing them is available and can be utilized with a little extra tooling.

The key to creating a multi-page form is to utilize sub forms, but to display only one such sub form per page. This allows you to submit a single sub form at a time and validate it, but not process the form until all sub forms are complete.

Example #1 Registration Form Example

Let's use a registration form as an example. For our purposes, we want to capture the desired username and password on the first page, then the user's metadata -- given name, family name, and location -- and finally allow them to decide what mailing lists, if any, they wish to subscribe to.

First, let's create our own form, and define several sub forms within it:

  1. span style="color: #808080; font-style: italic;">// Create user sub form: username and password
  2. 'username''required''label'      => 'Username:',
  3.                 'filters''StringTrim', 'StringToLower'),
  4.                 'validators''Alnum''Regex''/^[a-z][a-z0-9]{2,}$/''password''required''label'      => 'Password:',
  5.                 'filters''StringTrim'),
  6.                 'validators''NotEmpty''StringLength'// Create demographics sub form: given name, family name, and
  7.         // location
  8. 'givenName''required''label'      => 'Given (First) Name:',
  9.                 'filters''StringTrim'),
  10.                 'validators''Regex''/^[a-z][a-z0-9., \'-]{2,}$/i''familyName''required''label'      => 'Family (Last) Name:',
  11.                 'filters''StringTrim'),
  12.                 'validators''Regex''/^[a-z][a-z0-9., \'-]{2,}$/i''location''required''label'      => 'Your Location:',
  13.                 'filters''StringTrim'),
  14.                 'validators''StringLength'// Create mailing lists sub form
  15. 'none'        => 'No lists, please',
  16.             'fw-general'  => 'Zend Framework General List',
  17.             'fw-mvc'      => 'Zend Framework MVC List',
  18.             'fw-auth'     => 'Zend Framwork Authentication and ACL List',
  19.             'fw-services' => 'Zend Framework Web Services List''subscriptions''label'        =>
  20.                     'Which lists would you like to subscribe to?',
  21.                 'multiOptions''required''filters''StringTrim'),
  22.                 'validators''InArray'// Attach sub forms to main form
  23. 'user'  => $user,
  24.             'demog' => $demog,
  25.             'lists'

Note that there are no submit buttons, and that we have done nothing with the sub form decorators -- which means that by default they will be displayed as fieldsets. We will need to be able to override these as we display each individual sub form, and add in submit buttons so we can actually process them -- which will also require action and method properties. Let's add some scaffolding to our class to provide that information:

  1. span style="color: #808080; font-style: italic;">// ...
  2.  
  3.     /**
  4.      * Prepare a sub form for display
  5.      *
  6.      * @param  string|Zend_Form_SubForm $spec
  7.      * @return Zend_Form_SubForm
  8.      */'Invalid argument passed to ''()'/**
  9.      * Add form decorators to an individual sub form
  10.      *
  11.      * @param  Zend_Form_SubForm $subForm
  12.      * @return My_Form_Registration
  13.      */'FormElements''HtmlTag''tag' => 'dl',
  14.                                    'class' => 'zend_form')),
  15.             'Form'/**
  16.      * Add a submit button to an individual sub form
  17.      *
  18.      * @param  Zend_Form_SubForm $subForm
  19.      * @return My_Form_Registration
  20.      */'save''label'    => 'Save and continue',
  21.                 'required''ignore'/**
  22.      * Add action and method to sub form
  23.      *
  24.      * @param  Zend_Form_SubForm $subForm
  25.      * @return My_Form_Registration
  26.      */'/registration/process')
  27.                 ->setMethod('post'

Next, we need to add some scaffolding in our action controller, and have several considerations. First, we need to make sure we persist form data between requests, so that we can determine when to quit. Second, we need some logic to determine what form segments have already been submitted, and what sub form to display based on that information. We'll use Zend_Session_Namespace to persist data, which will also help us answer the question of which form to submit.

Let's create our controller, and add a method for retrieving a form instance:

  1.  

Now, let's add some functionality for determining which form to display. Basically, until the entire form is considered valid, we need to continue displaying form segments. Additionally, we likely want to make sure they're in a particular order: user, demog, and then lists. We can determine what data has been submitted by checking our session namespace for particular keys representing each subform.

  1. span style="color: #808080; font-style: italic;">// ...
  2. 'RegistrationController'/**
  3.      * Get the session namespace we're using
  4.      *
  5.      * @return Zend_Session_Namespace
  6.      *//**
  7.      * Get a list of forms already stored in the session
  8.      *
  9.      * @return array
  10.      *//**
  11.      * Get list of all subforms available
  12.      *
  13.      * @return array
  14.      *//**
  15.      * What sub form was submitted?
  16.      *
  17.      * @return false|Zend_Form_SubForm
  18.      *//**
  19.      * Get the next sub form to display
  20.      *
  21.      * @return Zend_Form_SubForm|false
  22.      */

The above methods allow us to use notations such as "$subForm = $this->getCurrentSubForm();" to retrieve the current sub form for validation, or "$next = $this->getNextSubForm();" to get the next one to display.

Now, let's figure out how to process and display the various sub forms. We can use getCurrentSubForm() to determine if any sub forms have been submitted (FALSE return values indicate none have been displayed or submitted), and getNextSubForm() to retrieve a form to display. We can then use the form's prepareSubForm() method to ensure the form is ready for display.

When we have a form submission, we can validate the sub form, and then check to see if the entire form is now valid. To do these tasks, we'll need additional methods that ensure that submitted data is added to the session, and that when validating the form entire, we validate against all segments from the session:

  1. span style="color: #808080; font-style: italic;">// ...
  2.  
  3.     /**
  4.      * Is the sub form valid?
  5.      *
  6.      * @param  Zend_Form_SubForm $subForm
  7.      * @param  array $data
  8.      * @return bool
  9.      *//**
  10.      * Is the full form valid?
  11.      *
  12.      * @return bool
  13.      */

Now that we have the legwork out of the way, let's build the actions for this controller. We'll need a landing page for the form, and then a 'process' action for processing the form.

  1. span style="color: #808080; font-style: italic;">// ...
  2. // Either re-display the current page, or grab the "next"
  3.         // (first) sub form
  4. 'index''index''index');
  5.         }
  6.  
  7.         // Valid form!
  8.         // Render information in a verification page
  9. 'verification');
  10.     }
  11. }

As you'll notice, the actual code for processing the form is relatively simple. We check to see if we have a current sub form submission, and if not, we go back to the landing page. If we do have a sub form, we attempt to validate it, redisplaying it if it fails. If the sub form is valid, we then check to see if the form is valid, which would indicate we're done; if not, we display the next form segment. Finally, we display a verification page with the contents of the session.

The view scripts are very simple:

  1. span style="color: #808080; font-style: italic;">// registration/index.phtml ?>
  2. // registration/verification.phtml ?>
  3. // Have to do this construct due to how items are stored in session
  4. // namespaces

Upcoming releases of Zend Framework will include components to make multi page forms simpler by abstracting the session and ordering logic. In the meantime, the above example should serve as a reasonable guideline on how to accomplish this task for your site.


Internationalization of Zend_Form