Helping ordinary people create extraordinary websites!

Zend Framework Tutorial

By Lyndon Baptiste
2008-08-13

Zend_Form

Let's assume we want to create a form where users can register. Creating forms that can be easily validated is a breeze with Zend_Form. There are a lot of different approaches to how forms can be created, in terms of delegating functionality. Some people choose to create classes that subclass zend form. However I have found that once the number of forms I have grow the number of classes increase exponentially. Instead I choose to have a form class for each controller that includes the creation of forms through calls to static methods. This way I can easily include the functionality within the models folder for a given module, using naming conventions that are consistent with those of controllers and still in the end have a Zend_Form object returned for easy manipulation. Instead I postfix the name of the class with the word "Form". Therefore in the models directory any forms I have relating to the IndexController will be found in the file IndexForm.php. So let's create this class and then add code to the controller that will make rendering it possible.

<?php
require_once 'Zend/Form.php';

class IndexForm {

public static function registerForm() {

require_once 'Zend/Form/Element/Text.php';
require_once 'Zend/Form/Element/Password.php';
require_once 'Zend/Form/Element/Radio.php';
require_once 'Zend/Form/Element/Submit.php';

$form = new Zend_Form();

$form->setAction('/default/index/save')
->setMethod('post')
->setAttrib('class', 'editor');

$email = new Zend_Form_Element_Text('email');
$password = new Zend_Form_Element_Password('password');
$gender = new Zend_Form_Element_Radio('gender');

$email->addValidator('EmailAddress')
->setRequired(true)
->addFilter('StringToLower')
->setLabel('Email:');

$password->setRequired(true)
->setLabel('Password:');

$gender->setLabel('Gender:')
->setSeparator(' ')
->addMultiOption('m', 'Male')
->addMultiOption('f', 'Female')
->removeDecorator('Errors');

$form->addElement($email)
->addElement($password)
->addElement($gender)
->addElement(new Zend_Form_Element_Submit('Submit'));

return $form;
}
}
?>
?>

The next great thing about having these static methods is that we can require only the files we need for a given form. Personally I prefer to create my forms using code, maybe being from a Java background, so if you do let's discuss the various elements. Zend_Form must be required. This class is the equivalent of a container onto which components can be added. The static method registerForm is my little convention insomuch that it corresponds with the name of the action. This is not absolutely necessary. From lines 8 to 17 I require the files representing XHTML elements of interest to the form. In our case, text boxes, password fields, radio buttons and the submit buttons. Line 15 to 17 sets up basic properties of interest to any form. As a parameter of setAction the module, controller, action we will like to post to is specified. Because these methods utilize the fluent interface (meaning at the end of the method call 'this' object is returned we can use the syntatical structure. Sometimes we may wish to set other attributes of the form. For this, the setAttrib method can be used which takes two parameters: the name of the attribute and the value we would like to set it to. Line 19 to 21 creates elements of the given type. The name we pass to the constructor will be interpreted as the name of the element when the XHTML form is rendered.

Filters and Validators can be added to these elements that we have created. There are various ways of adding validators. The qualifying name of the validator can be specified as a string parameter to the addValidator method. The same goes for filters. Another way would be to pass a reference to an named or anonymous instance of the class. For the email element, the email address validator is added. Similarly to Zend_Form these elements implement the fluent interface and enabling the shorthand access to the methods. To set the display label of the element the setLabel method is called. The programmer also has the option to specify whether or not the given field is required through passing of a boolean value to the method setRequired.

The means of setting validators and filters is consistent among elements. The only additionaly item I would like to highlight is for the cases of multioption elements such as the radio button. By default each radio button will be produced on a new line along with the label when the form is rendered. If you wish, you can modify this be making a call to setSeparator as illustrated on line 32. In the end it is best to return this form object. This comes in handy when we wish to set the values of an already created form as an example consider populating an edit form of a person. The setValue method can be used to accomplish just this.

Let us now create an action that can render this form.

public function registerAction() {
require_once './application/modules/default/models/IndexForm.php';
$this->view->form = IndexForm::registerForm();
$this->render();
}

I'm assuming you copied the action onto line 21. On line 23 the static method is called, creating and returning the form for storage in the already initialized view object. It will be necessary to create a register.phtml script. Once that is done paste the single line of code into the page

<?=$this->form?>

A request to /default/index/register should yield the results shown in Figure 4. If you've been successful so far you can view source to see what the form looks like. For ease i've listed include some CSS code that can be used to structure the form how "we know it". I'm assuming that you will copy the code into a default.css file located in the css folder contained in the webroot.





Tutorial pages:
 11 Votes

You might also want to check these out:


Leave a Comment on "Zend Framework Tutorial"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS