Saturday, April 7, 2012

Forms in Zend Framework. Getting rid of routines.

Once I have been asked to write an article to a magazine called phpsolutions. But it appeared that a subscription to this magazine is not free so my article is not available in a public access and could not be shared with a wide range of people and this fact concerns me a lot. As I have no any agreements with the magazine I've decided to publish this article so here it is... 

 

Introduction


Forms and form handling are important parts of the web development. Form handling consists of following stages:
- Form displaying
- Form data filtering
- Form data validation

Zend Framework provides very powerful component for forms handling. In a Zend Framework based application each form has it’s own class where form attributes are set, rules for filtering and validation are described. Please see the Listing 1 for the example

Listing 1. Zend_Form class example
<?php
class forms_ContactForm extends Zend_Form
{
     public function __construct($options = null)
     {
         parent::__construct($options);
         $this->setName('contact_us');
        
         $firstName = new Zend_Form_Element_Text('firstName');
         $firstName->setLabel('First name')
             ->setRequired(true)
             ->addValidator('NotEmpty');
        
         $email = new Zend_Form_Element_Text('email');
         $email->setLabel('Email address')
             ->addFilter('StringToLower')
             ->setRequired(true)
             ->addValidator('NotEmpty', true)
             ->addValidator('EmailAddress');

         $submit = new Zend_Form_Element_Submit('submit');
         $submit->setLabel('Contact us');
         $this->addElements(array($firstName, $email, $submit));
     }
}

So as you can see Zend_Form provides you abilities to manipulate form fields, to filter and validate form data.