Previous Next

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:

$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:

$form->setAction('/resource/process')
     ->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:

$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:

// Instantiating an element and passing to the form object:
$form->addElement(new Zend_Form_Element_Text('username'));

// Passing a form element type to the form object:
$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:

$username = new Zend_Form_Element_Text('username');

// Passing a Zend_Validate_* object:
$username->addValidator(new Zend_Validate_Alnum());

// Passing a validator name:
$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:

// Pass a pattern
$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:

// Make this element required:
$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:

$username->addFilter('StringtoLower');

The final element setup might look like this:

$username->addValidator('alnum')
         ->addValidator('regex', false, array('/^[a-z]/'))
         ->setRequired(true)
         ->addFilter('StringToLower');

// or, more compactly:
$username->addValidators(array('alnum',
        array('regex', false, '/^[a-z]/i')
    ))
    ->setRequired(true)
    ->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:

$form->addElement('text', 'username', array(
    'validators' => array(
        'alnum',
        array('regex', false, '/^[a-z]/i')
    ),
    'required' => true,
    'filters'  => array('StringToLower'),
));

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.

// Explicitly calling render(), and passing an optional view object:
echo $form->render($view);

// Assuming a view object has been previously set via setView():
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:

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:

$element->addDecorators(array(
    'ViewHelper',
    'Errors',
    array('HtmlTag', array('tag' => 'dd')),
    array('Label', array('tag' => 'dt')),
));

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

The above creates output like the following:

  • '123-abc' has not only alphabetic and digit characters
  • '123-abc' does not match against pattern '/^[a-z]/i'

(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:

$element->setOrder(10);

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

$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):

if ($form->isValid($_POST)) {
    // success!
} else {
    // failure!
}

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:

if ($form->isValidPartial($_POST)) {
    // elements present all passed validations
} else {
    // one or more elements tested failed validations
}

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:

$values = $form->getValues();

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

$unfiltered = $form->getUnfilteredValues();

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

$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:

if (!$form->isValid($_POST)) {
    echo $form;

    // or assign to the view object and render a view...
    $this->view->form = $form;
    return $this->render('form');
}

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:

$form = new Zend_Form();
$form->setAction('/user/login')
     ->setMethod('post');

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

// Create and configure password element:
$password = $form->createElement('password', 'password');
$password->addValidator('StringLength', false, array(6))
         ->setRequired(true);

// Add elements to form:
$form->addElement($username)
     ->addElement($password)
     // use addElement() as a factory to create 'Login' button:
     ->addElement('submit', 'login', array('label' => 'Login'));

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

class UserController extends Zend_Controller_Action
{
    public function getForm()
    {
        // create form as above
        return $form;
    }

    public function indexAction()
    {
        // render user/form.phtml
        $this->view->form = $this->getForm();
        $this->render('form');
    }

    public function loginAction()
    {
        if (!$this->getRequest()->isPost()) {
            return $this->_forward('index');
        }
        $form = $this->getForm();
        if (!$form->isValid($_POST)) {
            // Failed validation; redisplay form
            $this->view->form = $form;
            return $this->render('form');
        }

        $values = $form->getValues();
        // now try and authenticate....
    }
}

And a view script for displaying the form:

Please login:

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'):

[development]
; general form metainformation
user.login.action = "/user/login"
user.login.method = "post"

; username element
user.login.elements.username.type = "text"
user.login.elements.username.options.validators.alnum.validator = "alnum"
user.login.elements.username.options.validators.regex.validator = "regex"
user.login.elements.username.options.validators.regex.options.pattern = "/^[a-z]/i"
user.login.elements.username.options.validators.strlen.validator = "StringLength"
user.login.elements.username.options.validators.strlen.options.min = "6"
user.login.elements.username.options.validators.strlen.options.max = "20"
user.login.elements.username.options.required = true
user.login.elements.username.options.filters.lower.filter = "StringToLower"

; password element
user.login.elements.password.type = "password"
user.login.elements.password.options.validators.strlen.validator = "StringLength"
user.login.elements.password.options.validators.strlen.options.min = "6"
user.login.elements.password.options.required = true

; submit element
user.login.elements.submit.type = "submit"

You would then pass this to the form constructor:

$config = new Zend_Config_Ini($configFile, 'development');
$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!

Previous Next
Introduction to Zend Framework
Overview
Installation
Learning Zend Framework
Zend Framework Quick Start
Zend Framework & MVC Introduction
Create Your Project
Create A Layout
Create a Model and Database Table
Create A Form
Congratulations!
Autoloading in Zend Framework
Introduction
Goals and Design
Basic Autoloader Usage
Resource Autoloading
Conclusion
Plugins in Zend Framework
Introduction
Using Plugins
Conclusion
Getting Started with Zend_Layout
Introduction
Using Zend_Layout
Zend_Layout: Conclusions
Getting Started Zend_View Placeholders
Introduction
Basic Placeholder Usage
Standard Placeholders
View Placeholders: Conclusion
Understanding and Using Zend Form Decorators
Introduction
Decorator Basics
Layering Decorators
Rendering Individual Decorators
Creating and Rendering Composite Elements
Conclusion
Getting Started with Zend_Session, Zend_Auth, and Zend_Acl
Building Multi-User Applications With Zend Framework
Managing User Sessions In ZF
Authenticating Users in Zend Framework
Building an Authorization System in Zend Framework
Getting Started with Zend_Search_Lucene
Zend_Search_Lucene Introduction
Lucene Index Structure
Index Opening and Creation
Indexing
Searching
Supported queries
Search result pagination
Getting Started with Zend_Paginator
Introduction
Simple Examples
Pagination Control and ScrollingStyles
Putting it all Together
Zend Framework Reference
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Barcode
Introduction
Barcode creation using Zend_Barcode class
Zend_Barcode Objects
Zend_Barcode Renderers
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
The Cache Manager
Zend_Captcha
Introduction
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Zend_Currency
Introduction to Zend_Currency
Using Zend_Currency
Options for currencies
What makes a currency?
Where is the currency?
How does the currency look like?
How much is my currency?
Calculating with currencies
Exchanging currencies
Additional informations on Zend_Currency
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Db_Table_Definition
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dojo build layer support
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Basic usage
Previous Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_Feed_Reader
Zend_Feed_Writer
Zend_Feed_Pubsubhubbub
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
Advanced Usage of Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
Zend_Loader
Loading Files and Classes Dynamically
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Zend_Log
Overview
Writers
Formatters
Filters
Using the Factory to Create a Log
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Markup
Introduction
Getting Started With Zend_Markup
Zend_Markup Parsers
Zend_Markup Renderers
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_Oauth
Introduction to OAuth
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction
Creating and Loading PDF Documents
Save Changes to PDF Documents
Working with Pages
Drawing
Interactive Features
Document Info and Metadata
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Serializer
Introduction
Zend_Serializer_Adapter
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Storage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Amazon_Sqs
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_DeveloperGarden
Zend_Service_Flickr
Zend_Service_LiveDocx
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Zend_Service_SlideShare
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_WindowsAzure
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool
Using Zend_Tool On The Command Line
Extending Zend_Tool
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend_Tool Project Providers
Zend_Tool_Project Internals
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
ZendX_Console_Process_Unix
ZendX_Console_Process_Unix
ZendX_JQuery
Introduction
ZendX_JQuery View Helpers
ZendX_JQuery Form Elements and Decorators
Zend Framework Requirements
Introduction
Zend Framework Migration Notes
Zend Framework 1.10
Zend Framework 1.9
Zend Framework 1.8
Zend Framework 1.7
Zend Framework 1.6
Zend Framework 1.5
Zend Framework 1.0
Zend Framework 0.9
Zend Framework 0.8
Zend Framework 0.6
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information