Internationalization of Zend_Form | Zend_Form Programmer's Reference Guide | Zend_Gdata

# 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>
8. <dt><label for="address">Address:</label></dt>
9. <dd><input name="address" type="text" value="" /></dd>
11. <dt><label for="municipality">City:</label></dt>
12. <dd><input name="municipality" type="text" value="" /></dd>
14. <dt><label for="province">State:</label></dt>
15. <dd><input name="province" type="text" value="" /></dd>
17. <dt><label for="postal">Postal Code:</label></dt>
18. <dd><input name="postal" type="text" value="" /></dd>
19. </dl>
20. </fieldset>
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>
28. <dt><label for="address">Address:</label></dt>
29. <dd><input name="address" type="text" value="" /></dd>
31. <dt><label for="municipality">City:</label></dt>
32. <dd><input name="municipality" type="text" value="" /></dd>
34. <dt><label for="province">State:</label></dt>
35. <dd><input name="province" type="text" value="" /></dd>
37. <dt><label for="postal">Postal Code:</label></dt>
38. <dd><input name="postal" type="text" value="" /></dd>
39. </dl>
40. </fieldset>
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>
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>
9. <dt><label for="shipping-address">Address:</label></dt>
10. <dd><input name="shipping[address]" id="shipping-address"
11. type="text" value="" /></dd>
13. <dt><label for="shipping-municipality">City:</label></dt>
14. <dd><input name="shipping[municipality]" id="shipping-municipality"
15. type="text" value="" /></dd>
17. <dt><label for="shipping-province">State:</label></dt>
18. <dd><input name="shipping[province]" id="shipping-province"
19. type="text" value="" /></dd>
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>
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>
34. <dt><label for="billing-address">Address:</label></dt>
35. <dd><input name="billing[address]" id="billing-address"
36. type="text" value="" /></dd>
38. <dt><label for="billing-municipality">City:</label></dt>
39. <dd><input name="billing[municipality]" id="billing-municipality"
40. type="text" value="" /></dd>
42. <dt><label for="billing-province">State:</label></dt>
43. <dd><input name="billing[province]" id="billing-province"
44. type="text" value="" /></dd>
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>
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>
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. class My_Form_Registration extends Zend_Form
2. {
3. public function init()
4. {
5. // Create user sub form: username and password
6. $user = new Zend_Form_SubForm();
7. $user->addElements( array (
8. new Zend_Form_Element_Text('username', array (
9. 'required' => true,
10. 'label' => 'Username:',
11. 'filters' => array ('StringTrim', 'StringToLower'),
12. 'validators' => array (
13. 'Alnum',
14. array ('Regex',
15. false,
16. array ('/^[a-z][a-z0-9]{2,}$/'))
17. )
18. )),
20. new Zend_Form_Element_Password('password', array (
21. 'required' => true,
22. 'label' => 'Password:',
23. 'filters' => array ('StringTrim'),
24. 'validators' => array (
25. 'NotEmpty',
26. array ('StringLength', false, array (6))
27. )
28. )),
29. ));
31. // Create demographics sub form: given name, family name, and
32. // location
33. $demog = new Zend_Form_SubForm();
34. $demog->addElements( array (
35. new Zend_Form_Element_Text('givenName', array (
36. 'required' => true,
37. 'label' => 'Given (First) Name:',
38. 'filters' => array ('StringTrim'),
39. 'validators' => array (
40. array ('Regex',
41. false,
42. array ('/^[a-z][a-z0-9., \'-]{2,}$/i'))
43. )
44. )),
46. new Zend_Form_Element_Text('familyName', array (
47. 'required' => true,
48. 'label' => 'Family (Last) Name:',
49. 'filters' => array ('StringTrim'),
50. 'validators' => array (
51. array ('Regex',
52. false,
53. array ('/^[a-z][a-z0-9., \'-]{2,}$/i'))
54. )
55. )),
57. new Zend_Form_Element_Text('location', array (
58. 'required' => true,
59. 'label' => 'Your Location:',
60. 'filters' => array ('StringTrim'),
61. 'validators' => array (
62. array ('StringLength', false, array (2))
63. )
64. )),
65. ));
67. // Create mailing lists sub form
68. $listOptions = array (
69. 'none' => 'No lists, please',
70. 'fw-general' => 'Zend Framework General List',
71. 'fw-mvc' => 'Zend Framework MVC List',
72. 'fw-auth' => 'Zend Framwork Authentication and ACL List',
73. 'fw-services' => 'Zend Framework Web Services List',
74. );
75. $lists = new Zend_Form_SubForm();
76. $lists->addElements( array (
77. new Zend_Form_Element_MultiCheckbox('subscriptions', array (
78. 'label' =>
79. 'Which lists would you like to subscribe to?',
80. 'multiOptions' => $listOptions,
81. 'required' => true,
82. 'filters' => array ('StringTrim'),
83. 'validators' => array (
84. array ('InArray',
85. false,
86. array ( array_keys ($listOptions)))
87. )
88. )),
89. ));
91. // Attach sub forms to main form
92. $this->addSubForms( array (
93. 'user' => $user,
94. 'demog' => $demog,
95. 'lists' => $lists
96. ));
97. }
98. }

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. class My_Form_Registration extends Zend_Form
2. {
3. // ...
5. /**
6. * Prepare a sub form for display
7. *
8. * @param string|Zend_Form_SubForm $spec
9. * @return Zend_Form_SubForm
10. */
11. public function prepareSubForm($spec)
12. {
13. if ( is_string ($spec)) {
14. $subForm = $this->{$spec};
15. } elseif ($spec instanceof Zend_Form_SubForm) {
16. $subForm = $spec;
17. } else {
18. throw new Exception('Invalid argument passed to ' .
19. __FUNCTION__ . '()');
20. }
21. $this->setSubFormDecorators($subForm)
22. ->addSubmitButton($subForm)
23. ->addSubFormActions($subForm);
24. return $subForm;
25. }
27. /**
28. * Add form decorators to an individual sub form
29. *
30. * @param Zend_Form_SubForm $subForm
31. * @return My_Form_Registration
32. */
33. public function setSubFormDecorators(Zend_Form_SubForm $subForm)
34. {
35. $subForm->setDecorators( array (
36. 'FormElements',
37. array ('HtmlTag', array ('tag' => 'dl',
38. 'class' => 'zend_form')),
39. 'Form',
40. ));
41. return $this;
42. }
44. /**
45. * Add a submit button to an individual sub form
46. *
47. * @param Zend_Form_SubForm $subForm
48. * @return My_Form_Registration
49. */
50. public function addSubmitButton(Zend_Form_SubForm $subForm)
51. {
52. $subForm->addElement(new Zend_Form_Element_Submit(
53. 'save',
54. array (
55. 'label' => 'Save and continue',
56. 'required' => false,
57. 'ignore' => true,
58. )
59. ));
60. return $this;
61. }
63. /**
64. * Add action and method to sub form
65. *
66. * @param Zend_Form_SubForm $subForm
67. * @return My_Form_Registration
68. */
69. public function addSubFormActions(Zend_Form_SubForm $subForm)
70. {
71. $subForm->setAction('/registration/process')
72. ->setMethod('post');
73. return $this;
74. }
75. }

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. class RegistrationController extends Zend_Controller_Action
2. {
3. protected $_form;
5. public function getForm()
6. {
7. if (null === $this->_form) {
8. $this->_form = new My_Form_Registration();
9. }
10. return $this->_form;
11. }
12. }

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. class RegistrationController extends Zend_Controller_Action
2. {
3. // ...
5. protected $_namespace = 'RegistrationController';
6. protected $_session;
8. /**
9. * Get the session namespace we're using
10. *
11. * @return Zend_Session_Namespace
12. */
13. public function getSessionNamespace()
14. {
15. if (null === $this->_session) {
16. $this->_session =
17. new Zend_Session_Namespace($this->_namespace);
18. }
20. return $this->_session;
21. }
23. /**
24. * Get a list of forms already stored in the session
25. *
26. * @return array
27. */
28. public function getStoredForms()
29. {
30. $stored = array ();
31. foreach ($this->getSessionNamespace() as $key => $value) {
32. $stored[] = $key;
33. }
35. return $stored;
36. }
38. /**
39. * Get list of all subforms available
40. *
41. * @return array
42. */
43. public function getPotentialForms()
44. {
45. return array_keys ($this->getForm()->getSubForms());
46. }
48. /**
49. * What sub form was submitted?
50. *
51. * @return false|Zend_Form_SubForm
52. */
53. public function getCurrentSubForm()
54. {
55. $request = $this->getRequest();
56. if (!$request->isPost()) {
57. return false;
58. }
60. foreach ($this->getPotentialForms() as $name) {
61. if ($data = $request->getPost($name, false)) {
62. if ( is_array ($data)) {
63. return $this->getForm()->getSubForm($name);
64. break;
65. }
66. }
67. }
69. return false;
70. }
72. /**
73. * Get the next sub form to display
74. *
75. * @return Zend_Form_SubForm|false
76. */
77. public function getNextSubForm()
78. {
79. $storedForms = $this->getStoredForms();
80. $potentialForms = $this->getPotentialForms();
82. foreach ($potentialForms as $name) {
83. if (!in_array ($name, $storedForms)) {
84. return $this->getForm()->getSubForm($name);
85. }
86. }
88. return false;
89. }
90. }

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. class RegistrationController extends Zend_Controller_Action
2. {
3. // ...
5. /**
6. * Is the sub form valid?
7. *
8. * @param Zend_Form_SubForm $subForm
9. * @param array $data
10. * @return bool
11. */
12. public function subFormIsValid(Zend_Form_SubForm $subForm,
13. array $data)
14. {
15. $name = $subForm->getName();
16. if ($subForm->isValid($data)) {
17. $this->getSessionNamespace()->$name = $subForm->getValues();
18. return true;
19. }
21. return false;
22. }
24. /**
25. * Is the full form valid?
26. *
27. * @return bool
28. */
29. public function formIsValid()
30. {
31. $data = array ();
32. foreach ($this->getSessionNamespace() as $key => $info) {
33. $data[$key] = $info;
34. }
36. return $this->getForm()->isValid($data);
37. }
38. }

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. class RegistrationController extends Zend_Controller_Action
2. {
3. // ...
5. public function indexAction()
6. {
7. // Either re-display the current page, or grab the "next"
8. // (first) sub form
9. if (!$form = $this->getCurrentSubForm()) {
10. $form = $this->getNextSubForm();
11. }
12. $this->view->form = $this->getForm()->prepareSubForm($form);
13. }
15. public function processAction()
16. {
17. if (!$form = $this->getCurrentSubForm()) {
18. return $this->_forward('index');
19. }
21. if (!$this->subFormIsValid($form,
22. $this->getRequest()->getPost())) {
23. $this->view->form = $this->getForm()->prepareSubForm($form);
24. return $this->render('index');
25. }
27. if (!$this->formIsValid()) {
28. $form = $this->getNextSubForm();
29. $this->view->form = $this->getForm()->prepareSubForm($form);
30. return $this->render('index');
31. }
33. // Valid form!
34. // Render information in a verification page
35. $this->view->info = $this->getSessionNamespace();
36. $this->render('verification');
37. }
38. }

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. <?php // registration/index.phtml ?>
2. <h2>Registration</h2>
3. <?php echo $this->form ?>
5. <?php // registration/verification.phtml ?>
6. <h2>Thank you for registering!</h2>
7. <p>
8. Here is the information you provided:
9. </p>
11. <?
12. // Have to do this construct due to how items are stored in session
13. // namespaces
14. foreach ($this->info as $info):
15. foreach ($info as $form => $data): ?>
16. <h4><?php echo ucfirst ($form) ?>:</h4>
17. <dl>
18. <?php foreach ($data as $key => $value): ?>
19. <dt><?php echo ucfirst ($key) ?></dt>
20. <?php if ( is_array ($value)):
21. foreach ($value as $label => $val): ?>
22. <dd><?php echo $val ?></dd>
23. <?php endforeach;
24. else: ?>
25. <dd><?php echo $this->escape($value) ?></dd>
26. <?php endif;
27. endforeach; ?>
28. </dl>
29. <?php endforeach;
30. endforeach ?>

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 | Zend_Form Programmer's Reference Guide | Zend_Gdata