22 July 2009

Here is an example of a Zend Form

Let's make a Zend form for our contact page. I will finish the controller and mail functionality in a later post:

application/forms/contact.php
class Form_Contact extends Zend_Form
{
 public function init()
 {
  $hash = new Zend_Form_Element_Hash('hash');
  $hash->setSalt('zendweaves');
  
  $name = new Zend_Form_Element_Text('name');
  $name->setLabel('Name:')
   ->setRequired(true)
   ->addFilter('StripTags')
   ->addFilter('StringTrim')
   ->addValidator('NotEmpty', true)
   ->addValidator('Alpha', true, true);
   
  $subject = new Zend_Form_Element_Text('subject');
  $subject->setLabel('Subject:')
   ->setRequired(true)
   ->addFilter('StripTags')
   ->addFilter('StringTrim')
   ->addValidator('NotEmpty', true)
   ->addValidator('Alnum', true, true);
   
  $email = new Zend_Form_Element_Text('email');
  $email->setLabel('Email:')
   ->setRequired(true)
   ->addFilter('StripTags')
   ->addFilter('StringTrim')
   ->addValidator('NotEmpty', true)
   ->addValidator('EmailAddress', true);
   
  $message = new Zend_Form_Element_Textarea('message');
  $message->setLabel('Message:')
   ->setRequired(true)
   ->addFilter('StripTags')
   ->addFilter('StringTrim')
   ->addValidator('NotEmpty', true);
   
  $submit = new Zend_Form_Element_Submit('submit');
  $submit->setLabel('Submit')
   ->removeDecorator('Label');

  $cancel = new Zend_Form_Element_Submit('cancel');
  $cancel->setLabel('Cancel')
   ->removeDecorator('Label');

  
  $this->addElements(array($hash, $name, $email, $subject, $message, $submit, $cancel))
   ->setName('contactForm')
   ->setMethod('post')         
   ->setDecorators(array(
    array('Description'),
    array('FormElements'),
    array('HtmlTag', array('tag' => 'dl')),
    array('Form')
   ))
  ;
 }
}

You have to use Form_Zend as that is the namespace Zend uses. And what we have set in our autoloader. It extends Zend_Form (no suprise there). The function starts with init() and must be public.

My form has 7 elements. The hash element is for cross site request forgery (csrf) — I'll cover that in a later article. The rest is your expected elements — I'll also cover the filters and validators in a later article. What we did was to create each element seperately, at the end we added all the elements to the form. There we also set the name (or id) of the form, it's method and decorators. I use the default decorators and just style it appropriately with CSS. The only reason I set the decorators again is to give the form a description which I use for status messages after submits.

Take care

Tjorriemorrie

No comments:

Post a Comment