Documentation

Zend_Form Quick Start - Zend_Form

Zend_Form Quick Start

This quick start guide covers the basics of creating, validating, and rendering forms with Zend_Form.

Create a form object

Creating a form object is very simple: simply instantiate Zend_Form:

  1. $form = new Zend_Form;

For advanced use cases, you may want to create a Zend_Form subclass, but for simple forms, you can create a form programmatically using a Zend_Form object.

If you wish to specify the form action and method (always good ideas), you can do so with the setAction() and setMethod() accessors:

  1. $form->setAction('/resource/process')
  2.      ->setMethod('post');

The above code sets the form action to the partial URL "/resource/process" and the form method to HTTP POST. This will be reflected during final rendering.

You can set additional HTML attributes for the <form> tag by using the setAttrib() or setAttribs() methods. For instance, if you wish to set the id, set the "id" attribute:

  1. $form->setAttrib('id', 'login');

Add elements to the form

A form is nothing without its elements. Zend_Form ships with some default elements that render XHTML via Zend_View helpers. These are as follows:

  • button

  • checkbox (or many checkboxes at once with multiCheckbox)

  • hidden

  • image

  • password

  • radio

  • reset

  • select (both regular and multi-select types)

  • submit

  • text

  • textarea

You have two options for adding elements to a form: you can instantiate concrete elements and pass in these objects, or you can pass in simply the element type and have Zend_Form instantiate an object of the correct type for you.

Some examples:

  1. // Instantiating an element and passing to the form object:
  2. $form->addElement(new Zend_Form_Element_Text('username'));
  3.  
  4. // Passing a form element type to the form object:
  5. $form->addElement('text', 'username');

By default, these do not have any validators or filters. This means you will need to configure your elements with at least validators, and potentially filters. You can either do this (a) before you pass the element to the form, (b) via configuration options passed in when creating an element via Zend_Form, or (c) by pulling the element from the form object and configuring it after the fact.

Let's first look at creating validators for a concrete element instance. You can either pass in Zend_Validate_* objects, or the name of a validator to utilize:

  1. $username = new Zend_Form_Element_Text('username');
  2.  
  3. // Passing a Zend_Validate_* object:
  4. $username->addValidator(new Zend_Validate_Alnum());
  5.  
  6. // Passing a validator name:
  7. $username->addValidator('alnum');

When using this second option, you can pass constructor arguments in an array as the third parameter if the validator can accept tem:

  1. // Pass a pattern
  2. $username->addValidator('regex', false, array('/^[a-z]/i'));

(The second parameter is used to indicate whether or not failure of this validator should prevent later validators from running; by default, this is FALSE.)

You may also wish to specify an element as required. This can be done using an accessor or passing an option when creating the element. In the former case:

  1. // Make this element required:
  2. $username->setRequired(true);

When an element is required, a 'NotEmpty' validator is added to the top of the validator chain, ensuring that the element has a value when required.

Filters are registered in basically the same way as validators. For illustration purposes, let's add a filter to lowercase the final value:

  1. $username->addFilter('StringtoLower');

The final element setup might look like this:

  1. $username->addValidator('alnum')
  2.          ->addValidator('regex', false, array('/^[a-z]/'))
  3.          ->setRequired(true)
  4.          ->addFilter('StringToLower');
  5.  
  6. // or, more compactly:
  7. $username->addValidators(array('alnum',
  8.         array('regex', false, '/^[a-z]/i')
  9.     ))
  10.     ->setRequired(true)
  11.     ->addFilters(array('StringToLower'));

Simple as this is, repeating it this for every element in a form can be a bit tedious. Let's try option (b) from above. When we create a new element using Zend_Form::addElement() as a factory, we can optionally pass in configuration options. These can include validators and filters. To do all of the above implicitly, try the following:

  1. $form->addElement('text', 'username', array(
  2.     'validators' => array(
  3.         'alnum',
  4.         array('regex', false, '/^[a-z]/i')
  5.     ),
  6.     'required' => true,
  7.     'filters'  => array('StringToLower'),
  8. ));

Note: If you find you are setting up elements using the same options in many locations, you may want to consider creating your own Zend_Form_Element subclass and utilizing that class instead; this will save you typing in the long-run.

Render a form

Rendering a form is simple. Most elements use a Zend_View helper to render themselves, and thus need a view object in order to render. Other than that, you have two options: use the form's render() method, or simply echo it.

  1. // Explicitly calling render(), and passing an optional view object:
  2. echo $form->render($view);
  3.  
  4. // Assuming a view object has been previously set via setView():
  5. echo $form;

By default, Zend_Form and Zend_Form_Element will attempt to use the view object initialized in the ViewRenderer, which means you won't need to set the view manually when using the Zend Framework MVC. To render a form in a view, you simply have to do the following:

  1. <?php echo $this->form ?>

Under the hood, Zend_Form uses "decorators" to perform rendering. These decorators can replace content, append content, or prepend content, and can fully introspect the element passed to them. As a result, you can combine multiple decorators to achieve custom effects. By default, Zend_Form_Element actually combines four decorators to achieve its output; setup looks something like this:

  1. $element->addDecorators(array(
  2.     'ViewHelper',
  3.     'Errors',
  4.     array('HtmlTag', array('tag' => 'dd')),
  5.     array('Label', array('tag' => 'dt')),
  6. ));

(Where <HELPERNAME> is the name of a view helper to use, and varies based on the element.)

The above creates output like the following:

  1. <dt><label for="username" class="required">Username</dt>
  2. <dd>
  3.     <input type="text" name="username" value="123-abc" />
  4.     <ul class="errors">
  5.         <li>'123-abc' has not only alphabetic and digit characters</li>
  6.         <li>'123-abc' does not match against pattern '/^[a-z]/i'</li>
  7.     </ul>
  8. </dd>

(Albeit not with the same formatting.)

You can change the decorators used by an element if you wish to have different output; see the section on decorators for more information.

The form itself simply loops through the elements, and dresses them in an HTML <form>. The action and method you provided when setting up the form are provided to the <form> tag, as are any attributes you set via setAttribs() and family.

Elements are looped either in the order in which they were registered, or, if your element contains an order attribute, that order will be used. You can set an element's order using:

  1. $element->setOrder(10);

Or, when creating an element, by passing it as an option:

  1. $form->addElement('text', 'username', array('order' => 10));

Check if a form is valid

After a form is submitted, you will need to check and see if it passes validations. Each element is checked against the data provided; if a key matching the element name is not present, and the item is marked as required, validations are run with a NULL value.

Where does the data come from? You can use $_POST or $_GET, or any other data source you might have at hand (web service requests, for instance):

  1. if ($form->isValid($_POST)) {
  2.     // success!
  3. } else {
  4.     // failure!
  5. }

With AJAX requests, you can sometimes get away with validating a single element, or groups of elements. isValidPartial() will validate a partial form. Unlike isValid(), however, if a particular key is not present, it will not run validations for that particular element:

  1. if ($form->isValidPartial($_POST)) {
  2.     // elements present all passed validations
  3. } else {
  4.     // one or more elements tested failed validations
  5. }

An additional method, processAjax(), can be used for validating partial forms. Unlike isValidPartial(), it returns a JSON-formatted string containing error messages on failure.

Assuming your validations have passed, you can now fetch the filtered values:

  1. $values = $form->getValues();

If you need the unfiltered values at any point, use:

  1. $unfiltered = $form->getUnfilteredValues();

If you on the other hand need all the valid and filtered values of a partially valid form, you can call:

  1. $values = $form->getValidValues($_POST);

Get error status

Did your form have failed validations on submission? In most cases, you can simply render the form again, and errors will be displayed when using the default decorators:

  1. if (!$form->isValid($_POST)) {
  2.     echo $form;
  3.  
  4.     // or assign to the view object and render a view...
  5.     $this->view->form = $form;
  6.     return $this->render('form');
  7. }

If you want to inspect the errors, you have two methods. getErrors() returns an associative array of element names / codes (where codes is an array of error codes). getMessages() returns an associative array of element names / messages (where messages is an associative array of error code / error message pairs). If a given element does not have any errors, it will not be included in the array.

Putting it together

Let's build a simple login form. It will need elements representing:

  • username

  • password

  • submit

For our purposes, let's assume that a valid username should be alphanumeric characters only, start with a letter, have a minimum length of 6, and maximum length of 20; they will be normalized to lowercase. Passwords must be a minimum of 6 characters. We'll simply toss the submit value when done, so it can remain unvalidated.

We'll use the power of Zend_Form's configuration options to build the form:

  1. $form = new Zend_Form();
  2. $form->setAction('/user/login')
  3.      ->setMethod('post');
  4.  
  5. // Create and configure username element:
  6. $username = $form->createElement('text', 'username');
  7. $username->addValidator('alnum')
  8.          ->addValidator('regex', false, array('/^[a-z]+/'))
  9.          ->addValidator('stringLength', false, array(6, 20))
  10.          ->setRequired(true)
  11.          ->addFilter('StringToLower');
  12.  
  13. // Create and configure password element:
  14. $password = $form->createElement('password', 'password');
  15. $password->addValidator('StringLength', false, array(6))
  16.          ->setRequired(true);
  17.  
  18. // Add elements to form:
  19. $form->addElement($username)
  20.      ->addElement($password)
  21.      // use addElement() as a factory to create 'Login' button:
  22.      ->addElement('submit', 'login', array('label' => 'Login'));

Next, we'll create a controller for handling this:

  1. class UserController extends Zend_Controller_Action
  2. {
  3.     public function getForm()
  4.     {
  5.         // create form as above
  6.         return $form;
  7.     }
  8.  
  9.     public function indexAction()
  10.     {
  11.         // render user/form.phtml
  12.         $this->view->form = $this->getForm();
  13.         $this->render('form');
  14.     }
  15.  
  16.     public function loginAction()
  17.     {
  18.         if (!$this->getRequest()->isPost()) {
  19.             return $this->_forward('index');
  20.         }
  21.         $form = $this->getForm();
  22.         if (!$form->isValid($_POST)) {
  23.             // Failed validation; redisplay form
  24.             $this->view->form = $form;
  25.             return $this->render('form');
  26.         }
  27.  
  28.         $values = $form->getValues();
  29.         // now try and authenticate....
  30.     }
  31. }

And a view script for displaying the form:

  1. <h2>Please login:</h2>
  2. <?php echo $this->form ?>

As you'll note from the controller code, there's more work to do: while the submission may be valid, you may still need to do some authentication using Zend_Auth or another authorization mechanism.

Using a Zend_Config Object

All Zend_Form classes are configurable using Zend_Config; you can either pass a Zend_Config object to the constructor or pass it in with setConfig(). Let's look at how we might create the above form using an INI file. First, let's follow the recommendations, and place our configurations into sections reflecting the release location, and focus on the 'development' section. Next, we'll setup a section for the given controller ('user'), and a key for the form ('login'):

  1. [development]
  2. ; general form metainformation
  3. user.login.action = "/user/login"
  4. user.login.method = "post"
  5.  
  6. ; username element
  7. user.login.elements.username.type = "text"
  8. user.login.elements.username.options.validators.alnum.validator = "alnum"
  9. user.login.elements.username.options.validators.regex.validator = "regex"
  10. user.login.elements.username.options.validators.regex.options.pattern = "/^[a-z]/i"
  11. user.login.elements.username.options.validators.strlen.validator = "StringLength"
  12. user.login.elements.username.options.validators.strlen.options.min = "6"
  13. user.login.elements.username.options.validators.strlen.options.max = "20"
  14. user.login.elements.username.options.required = true
  15. user.login.elements.username.options.filters.lower.filter = "StringToLower"
  16.  
  17. ; password element
  18. user.login.elements.password.type = "password"
  19. user.login.elements.password.options.validators.strlen.validator = "StringLength"
  20. user.login.elements.password.options.validators.strlen.options.min = "6"
  21. user.login.elements.password.options.required = true
  22.  
  23. ; submit element
  24. user.login.elements.submit.type = "submit"

You would then pass this to the form constructor:

  1. $config = new Zend_Config_Ini($configFile, 'development');
  2. $form   = new Zend_Form($config->user->login);

and the entire form will be defined.

Conclusion

Hopefully with this little tutorial, you should now be well on your way to unlocking the power and flexibility of Zend_Form. Read on for more in-depth information!

Copyright

© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts