jump to navigation

Zend Framework : Creating Forms with the Zend_Form component May 1, 2011

Posted by Tournas Dimitrios in Zend Framework v1.10.

This article will present the Zend_Form component , a step by step walk through for a newcomer to the Zend Framework . The reader must have a basic knowledge of how to build a form with PHP , I ‘ll not explain terminology related to form development . The final result will be a form that contains all the fundamental functionality like : validation , filtering , reset and captcha . Actually this article is part of the series ” Building a simple web application with the Zend Framework ” , so a future article will incorporate this form on a real application .

Zend_Form makes use of several Zend Framework components to accomplish its goals, including Zend_Config , Zend_Validate , Zend_Filter , Zend_Loader_PluginLoader , and optionally Zend_View .

The Zend_Form component let’s you create forms using an object-oriented design model . As Zend provides  al the fundamental code , you don’t have to write code for manipulating complex functionality like validation or filtering and concentrate your energy to the final result  . Each element in the form is an Zend_Form_Element_* object , where the asterisk can be a TextField , Button , Password field , Submit button …… The concept is simple :

  • First create a form object and set it’s properties ,
  • Creating (instantiation in OOP terminology ) new form elements
  • Assigning filters / validators to each element
  • Dispatch (display) the form

Download the project’s source code and use it as reference , because I’ll only focus on the details . To make the preparation of this article more pleasant to me , I have used the “skeleton” of a previous article (Zend Framework :Basic example of the Zend_View Placeholder ) . Just add another controller ( RegisterController ) and one action ( loginAction ) and you are ready to start building on top of previous project . That’s the magic of the MVC design pattern , extensibility with no headache   .

We could of course create a separate form object Class , but for this article the code will be hosted inside the controller , as my intension is to demonstrate the basic concepts of the Zend_Form component . Really it doesn’t matter the concepts remain the same on both implementations .

First create a form object and set it’s properties :

Creating an form object is simple as instantiation a new class in OOP terminology .
$form = new Zend_Form() ;

As in OOP setting properties can be done through setters , so configuring the newly created form class can be done through setters . The following table demonstrates the possible setters for a Zend form :

Configuring the Form through “setters”
setAction Defines the action attribute when submitt is pressed (accepts a single String value)
setMethod Defines what method will be used form transferring the data ( POST , GET )
setName Defines the name of the form (cannot be empty )
setDescription Defines an description for the form
setAttrib Define a sngle attribute to the form
setAttribs Defines multiple attributes a once as an array
setEnctype Defines the encoding type of the transferred data

A practical example :

$form = new Zend_Form();
	->setDescription('hello My_firstForm')
       ->setAttrib('enctype', 'multipart/form-data');

Creating (instantiation in OOP terminology ) new form elements : 

Actually each form element is provided to us in the form of a Class . Zend has 19 different classes to help us build our form . Of course we can extend these Classes to create custom functionality .

Creating elements is simple as :
$username = $form->createElement(‘text’, ‘username’) ;

=====  OR  ====
$username = new Zend_Form_Element_Text(‘name’) ;

On the first example , the first option defines the type of element (see table below ) , the second option is a unique name , so that we can refer to that specific element when we need ( assigning filters  , reading values of the element ) and finally a third optional Zend_Config object .

Type of form elements and the corresponding Zend Class
text Zend_Form_Element_Text
textarea Zend_Form_Element_TextArea
password Zend_Form_Element_Password
hidden Zend_Form_Element_Hidden
file Zend_Form_Element_File
hash Zend_Form_Element_Hash
image Zend_Form_Element_Image
button Zend_Form_Element_Button
reset Zend_Form_Element_Reset
select (drop down menu) Zend_Form_Element_Select
submit Zend_Form_Element_Submit
checkbox Zend_Form_Element_Checkbox
radio Zend_Form_Element_Radio
multicheckbox Zend_Form_Element_Image

The complete list of elements with a good description is here .

Practical example :

$form = new Zend_Form();

// Create and configure username element:
$username = $form->createElement('text', 'username');

Assigning filters / validators to each element :

Filters and validators are again provided to us in the form of Classes . This is the most important part of the form development route and according the official definition :

A validator examines its input with respect to some requirements and produces a boolean result – whether the input successfully validates against the requirements. If the input does not meet the requirements, a validator may additionally provide information about which requirement(s) the input does not meet. The Zend_Validate component provides a set of commonly needed validators. It also provides a simple validator chaining mechanism by which multiple validators may be applied to a single datum in a user-defined order.

The Zend_Validate component contains the following list of validators :

Validators Classes of the Zend
Alpha Allows only alphabetic characters
Alnum Allows only numeric characters
Barcode Validating the barcode
Between Ranges between min/max values
Ccnum Credit Cart number
Date Returns true if $value is a valid date of the format YYYY-MM-DD
Digits Allows only digits
EmailAddress Zend_Validate_EmailAddress allows you to validate an email address
Float Allows only Float numbers
StringLength Checks that the given string is between a min/max value
Visit the reference guide for a complete list of components

The Zend_Filter component contains the following list of Filters :

Filters Classes of the Zend
Alnum Returns only alphanumeric characters
Alpha Returns only alphabetic characters
Digits Returns only digits in a string
HtmlEntities Encodes the string and returns the encoded value of a string
Int Returns only integers values
StringToLower Removes \n markers from the string
Visit the reference guide for a complete list of components

A practical example :

$form = new Zend_Form();

// Create and configure username element:
$username = $form->createElement('text', 'username');
         ->addValidator('regex', false, array('/^[a-z]+/'))
         ->addValidator('stringLength', false, array(6, 20))
		 ->setLabel('Username : ***')

Here we apply the fluent interfaces technique for assigning options (formating) to the elements .

Dispatch (display) the form :

This can be done in two different ways :

  1. Directly from the controller action : echo $form->render($view) ;
  2. Assigning the form to an variable where the view will handle the display of that variable :
    $this->view->form = $form ;

The final result on our browser is  :

Download the code of this project .

Links :


No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s