Wednesday, July 1, 2009

Zend Form Decorators

I’d felt a lot of pain when I first used Zend_Form. The reason was that I wasn’t able to layout form elements the way I wanted them to be. Zend was rendering elements in dt and dd whilst I was looking forward to place them in row and cells.
In short I wasn’t aware of Zend_Form decorators in the beginning and when I studied them for some time I felt uncomfortable using them.
So I decided to use html forms in my phtml files-template file. Though by doing so I achieved the desired layout however I missed entire facilities/functionalities that Zend_Form component provide us such as validation, filtering, dispaying error messages and so on.
When I first created form with Zend_Form component I was served with layout like the following.


Label on the top of the text/ password element.

This is because Zend Framework render form label in "dt" tag and text/password form element in "dt","dd" tag and put entire form element in "dl" tag by default.

Code rendered was

<form method="post" action="">

<dl class="zend_form">
<dt><label for="agencyName" class="optional">User Name:</label></dt>
<dd>
<input type="text" name="agencyName" id="agencyName" value="">
</dd>
<dt><label for="advertiserName" class="optional">Password</label></dt>
<dd>
<input type="text" name="advertiserName" id="advertiserName" value="">
</dd>
<dt>&nbsp;</dt>
<dd>
<input type="submit" name="submit" id="submit" value="Login">
</dd>
<dl>
</form>


This was not the layout I was looking for. I was looking for
layout like the following.



To create form as above one need to put label and individual form element in "td" tag, put that "td" tag in "tr" tag and put all these in "table" tag. E.g

<form action="" method="post">

<table>
<tr>
<td><label for="username" class="optional">User Name:</label></td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td><label for="password" class="optional">Password</label></td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" id="submit" value="Login"></td>
</tr>
</table>
</form>


Zend form decorators can be used to create above form.

If you are beginner or have little experience working with zend, you may be facing difficulties in rendering Form using Zend_Form the way you want.

In this post I am providing indepth and comprehensive study of how to use Zend_Form_Decorators.

So let’s get started.

Although in the beginning you may find it difficult to use Zend_Form decorators, however once you get used to it and understand the basics, you will find these quite easy, helpful and interesting.

To create the login form in the figure 2. you will need the following code

class forms_LoginForm extends Zend_Form

{

public function __construct($option=null)
{

parent::__construct($option);

$this->setMethod('post');

$username=$this->CreateElement('text','username')

->setLabel('User Name:');

$username->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$password=$this->CreateElement('text','password')

->setLabel('Password');

$password->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$submit=$this->CreateElement('submit','submit')

->setLabel('Login');

$submit->setDecorators(array(

'ViewHelper',
'Description',
'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'td',
'colspan'=>'2','align'=>'center')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$this->addElements(array(

$username,
$password,
$submit

));

$this->setDecorators(array(

'FormElements',
array(array('data'=>'HtmlTag'),array('tag'=>'table')),
'Form'

));

}
}


Explanation:

First we extend our form from Zend_From and define our constructor. It is necessary to call parent class constructor before defining anything in your own constructor-by doing so our form will inherit all the functionality of Zend_Form.

After calling parent constructor we set our form method by simply $this->setMethod(‘post’).

Next we create text element and set its label.

The lines after setting label of the form are important because these lines give new look to our form. The code is quite simple. We call setDecorators() method of the form to override the default decorators behavior of the form.
The code
$username->setDecorators(array(


'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));


is very simple. We are skipping “ViewHelper”, “Description” and “Errors” for now. We will explain it some other time. We can define our decorators for these things as well if we need in future. However leave it as these are for now.

After “Errors” we define array which tell Zend to override the default decorators of
<input name="”username”" type="”text”">

. By doing so zend will wrap "input" tag in .

Next array define tag for label and put label in td tag as
<td><label ..></td>

.

Next array define tag for the row of the form. This wrap
<label ..>and <input>


in tr tag. The above code will create

<tr>


<td>User Name:</td>

<td><input type=”text” name=”username”></td>

</tr>


However defining decorators for the submit button we have change the code a lit bit.

As label is appearing on the button so we don’t need to define decorator for the label. By leaving decorator for label undefined, it means zend will use its default decorator for the label of the submit button.

And as we want to put button at the center of the row, so we have defined

array(array('data'=>'HtmlTag'), array('tag' => 'td',

'colspan'=>'2','align'=>'center')),


This will create html as

<td colspan=”2” align=”center”><input type=”submit” ….></td>



Next we add elements to form as
$this->addElements(array(


$username,
$password,
$submit

));


At the end we define decorators for the form-to wrap form elements in the html tag.

I have already said that zend wrap entire element in "dl" tag.

As we have wrap element in the "tg" and "tr" tag properly. So we need to wrap these "td" and "tr"’ in the "table" tag. To do so we have defined
$this->setDecorators(array(


'FormElements',
array(array('data'=>'HtmlTag'),array('tag'=>'table')),
'Form'

));


This code will wrap all "tr" in "table" tag.

Although this form is simple and contain only two fields however you can create very large form by following this procedure.

Next I going to create a form that may help lot of souls. First see the following form.


You can clearly see we have put all the form elements in the single row.

The html of the above form is

<table>

<tr>
<td>
<label for="username" class="optional">User Name:</label>
</td>
<td><input type=”text” name=”username”></td>
<td>
<label for="password" class="optional">Password</label>
</td>
<td><input type=”password” name=”password”></td>
<td align="center">
<input type="submit" name="submit" id="submit" value="Login"></td>
</tr>

</table>


You can clearly see that we have wrapped the elements in tags and then wrap those "td" tags in single "tr" tag and then "table" . To create the above form we will make very little changes in our code above.

The new code would be

class forms_LoginForm extends Zend_Form

{

public function __construct($option=null)
{

parent::__construct($option);

$this->setMethod('post');

$username=$this->CreateElement('text','username')

->setLabel('User Name:');

$username->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr', 'openOnly'=>true))

));

$password=$this->CreateElement('text','password')

->setLabel('Password');

$password->setDecorators(array(

'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),

));

$submit=$this->CreateElement('submit','submit')

->setLabel('Login');

$submit->setDecorators(array(

'ViewHelper',
'Description',
'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'td',
'colspan'=>'2','align'=>'center')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr', 'closeOnly'=>'true'))

));

$this->addElements(array(

$username,
$password,
$submit

));

$this->setDecorators(array(

'FormElements',
array(array('data'=>'HtmlTag'),array('tag'=>'table')),
'Form'

));

}
}

You can see we done very minor changes in our form.

In the first element “username” setDecorators() we have changed our array as

$username->setDecorators(array(


'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr', 'openOnly'=>true))

));


The only changes are in the last line of the array. We have now set ‘openOnly’ => true for the “row”. It means that we are wrapping elements of username in , however we are putting but opening it only- tag would not be closed when Zend will render this element.

Next

$password->setDecorators(array(


'ViewHelper',
'Description',
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),

));

Here we have defined only two arrays -third one is missing. The reason is we are wrapping elements in the "td" tag putting nothing for the row.

At the final change are made in the submit element setDecorators() method call as
$submit->setDecorators(array(


'ViewHelper',
'Description',
'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'td',
'colspan'=>'2','align'=>'center')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr', 'closeOnly'=>'true'))

));

Here also we have made changes in the last line-array(array(‘row’)…..). we have defined ‘closeOnly’ => ‘true’. This will close the tag opened in the first element setDecorators() section.

The rest of the code is same.
The rest of the code is same.

In almost all the websites where you find form will compulsory field indicate those fields either by placing text or image next to that field.

Zend_Form setDescription() can help you out and give you an easy way to achieve this goal. Look at the following form.


In the form above we have placed image next to our username field to tell the user that username is compulsory field.

To achieve this you will need to do very little changes in your previous form.

Code to create the above form is

class forms_LoginForm extends Zend_Form

{

public function __construct($option=null)
{

parent::__construct($option);

$this->setMethod('post');

$email = $this->CreateElement('text','username')

->setLabel('User Name:')

->setDescription('path/to/image');

$email->setDecorators(array(

'ViewHelper',
array('Description',array('tag'=>'','escape'=>false)),
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$password=$this->CreateElement('text','password')

->setLabel('Password')
->setDescription('path/to/image');

$password->setDecorators(array(

'ViewHelper',
array('Description',array('tag'=>'','escape'=>false)),
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$submit=$this->CreateElement('submit','submit')

->setLabel('Login');

$submit->setDecorators(array(

'ViewHelper',
'Description',
'Errors', array(array('data'=>'HtmlTag'), array('tag' => 'td',
'colspan'=>'2','align'=>'center')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

$this->addElements(array(

$username,
$password,
$submit

));

$this->setDecorators(array(

'FormElements',

array(array('data'=>'HtmlTag'),array('tag'=>'table')),

'Form'

));

}
}


If you compare the first form and this form code, you will see we have done very minor changes. If you compare this for with the first one, you will easily find the changes. However I will define these change for the beginners.

First we have added setDescription() method to our email and password elements of the form. This will add image as a description, however by default Zend will render description at the next row of the email as well as password fields. To put these images will need to define decorators for it. The only changes we will need to do in the setDecorators() methods are
Array(‘Description’,array(‘tag’=>’’,’escape’=>false)) at the place of “Description”. Look at the following code.
$email->setDecorators(array(


'ViewHelper',
array('Description',array('tag'=>'','escape'=>false)),
'Errors',
array(array('data'=>'HtmlTag'), array('tag' => 'td')),
array('Label', array('tag' => 'td')),
array(array('row'=>'HtmlTag'),array('tag'=>'tr'))

));

you can clearly see these changes in line 3. we have defined decorators for the description of the form element.

61 comments:

  1. Thanks boss, u r gr8........
    I've been looking for this code since past 6 months but unable to understand the use of zend form decorators. But this small demo application helps me lot to understand about them. But I still can not figure out the complete structure of $decorator parameter defined by zend framework. Can u plz help me with that.

    Manish Sharma
    (Software Engg.)
    (Delhi,India)

    ReplyDelete
  2. You will need to read and play with decorator more for complete understanding. It took some time, however once you master, you will using it in your application.
    It said, read more and try to implement.
    Zend documentation is good place to start.

    ReplyDelete
  3. My problem is I'm unable to implement decorator to captcha. I tried , I read each n every forum (including zend forums and manual) but didn't get any clue on how to implement decorator to captcha. I teared apart all zend library, but didn't able to diagnose that why captcha is not coming inside table. I tried your way as you have applied decorators to normal form element but it didn't work out. Can u plz help me with that.

    Manish Sharma
    (Software Engg.)
    (Delhi, India)

    ReplyDelete
  4. Excellent tutorial about the Zend Framework Form Decorators.
    Great resource.

    ReplyDelete
  5. Nice tutorial man . Really good one to start for every one new to Zend Framework.

    Thanks

    ReplyDelete
  6. <tr>
    <th>Email : </th >
    <th>Phone : </th>
    </tr>
    <tr>
    <td>&lt input id="email" name="email" value="" size="25" type="text" >&lt/td>
    <td>&lt input id="phone" name="phone" value="" size="25" type="text" >&lt/td>
    </tr>

    How can I display a form like this ?

    ReplyDelete
  7. Awesome tutorial, just what I was looking for.
    Clean, clear and usefull, just the way I like it ;)

    Kepp up the good work
    Andy

    ReplyDelete
  8. Hi there,
    first of all: excellent tutorial! But I've some errors when I try to set decorators for a file element. Anyone familiar with these?

    ReplyDelete
  9. i am new to zend. I got whole site helpful.it provides best tututorials to learn zend.this is also awesome.
    thanks Faheem

    ReplyDelete
  10. When I compare the HTML output and the PHP code needed to get it, I sometimes reconsider using Zend Form. The Zend Framework is great, but this is too much pain to get the HTML be rendered as you want. If you use Zend Forms only to validate data, you may prefer use an homemade validation method. That's my opinion, I wonder what do you think.

    ReplyDelete
  11. Zend_Form is one on the most fabulous component with Zend Framework. Beside validation, it provide you easy way of populating your form in case of editing, easy way for uploading files, implement internationalization and localization. Long story short; it has many advantages. The only difficulty is learning how to use decorators.
    give it try sometime, you will see how nice it is to create html form using Zend_Form.

    ReplyDelete
  12. Hi..

    nice tutorial....
    i have a query..
    i have a zend form with two radio buttons having same name.when rendered dey lie far apart.i hav given align= left stil its nt wrkin?any help?

    ReplyDelete
  13. Thank you very much for this stuff, i saved your whole page in my computer, may be just missing how to create personnal decorators and avoiding creating those in each form.
    Great help found here, thank you !!!

    ReplyDelete
  14. Great post -- I would just be cautious about using decorators in this way. Relying on CSS to style your layout allows your code to be much more reusable. Perhaps you can add class attributes to each of your login form elements... then use CSS to build the desired look.

    ReplyDelete
  15. Thanks Faheem.. great stuff... :)

    ReplyDelete
  16. it maybe good but i dont understand anything here clearly , still finding some good tutorial

    ReplyDelete
  17. nice. blog. really i got the complete idea of it.
    but the last description will not working.
    bt trully nice..

    ReplyDelete
  18. hi,

    Nice titorial,
    can you please explain how to display error/validation message in the tr td Validation Msg td tr
    Thanks
    Vaibhav

    ReplyDelete
  19. Many thanks to you
    you resolve a problem wich gives me many headakes since hours
    very good job

    ReplyDelete
  20. This is great article i love u

    ReplyDelete
  21. Help me to use Decorators for display like this:
    &ltlabel>User Name:&lt/label>
    &ltinput name="username" type="text" id="username" />
    &ltlabel>Password:&lt/label>
    &ltinput type="password" name="password" id="password" />

    ReplyDelete
  22. Thnk you very much. Following your words, you saved my soul ;)

    ReplyDelete
  23. Thank you.how can i validate check box and show error message like other fields e.g. textbox,password.

    ReplyDelete
  24. Saved my life!

    ReplyDelete
  25. that was very helpful,tnxxxx
    it really helps
    love u man!

    ReplyDelete
  26. it helped me a great. thank you so much

    zahir
    sydney
    developer

    ReplyDelete
  27. thnx a lot !!!
    you belong to the problem solvers the world can need much more of !!!!!

    ReplyDelete
  28. i like how you explain zend form decorators in the simple way :) now i now a little how to use it in my zend framework application.its good for beginner, for more advanced users should go to zend documentation.

    ReplyDelete
  29. Hello

    Thank U a lot! I'm brazilian and tried hard to found a solution for this problem. In my case I needed to add 2 or more buttons at the same td tag element. Now it's working. Thank U!

    See ya!

    ReplyDelete
  30. Thank you a lot!! I also tried hard to find a solution, and your explanation is simply the best!

    ReplyDelete
  31. Thanks a lot, Its really good

    ReplyDelete
  32. Its relay very practical and helpful example ...
    Thanks ...

    ReplyDelete
  33. Thanx dude....!Keep Helping to other...Thanx a lot

    ReplyDelete
  34. This is a nice article..
    Its very easy to understand ..
    And this article is using to learn something about it..

    c#, dot.net, php tutorial

    Thanks a lot..!

    ReplyDelete
  35. Nice post. Can you maybe talk about how to decorate the errors. I am trying to get the errors into a table cell next to the input field but I cannot get it to work. Any advice would be appreciated.

    ReplyDelete
  36. thanks a lot ! I tried to look for this solution ..

    ReplyDelete
  37. Terrific work! This is the type of information that should be shared around the web. Shame on the search engines for not positioning this post higher!

    nolvadex

    ReplyDelete
  38. good, i have a question!
    how can i change the message displayed by the error decorator.

    ReplyDelete
  39. Another way to manipulate zend form.
    My intention was to have:
    ----------------------------------
    label: input label: input
    label: input label: input
    ----------------------------------

    I put div-s around the form with id=addnewphrases

    To get a new row I added a decorations containing a
    -tag
    $text->addDecorators($decorators);

    #addnewphrases dl.zend_form {
    width:1000px;
    }
    #addnewphrases .zend_form dt {
    display:inline;
    float: left;
    width:150px;
    clear:none;
    }
    #addnewphrases .zend_form dd {
    display:inline;
    float: left;
    margin-right:40px;
    }
    #addnewphrases .zend_form #textcontent ,
    #addnewphrases .zend_form #textcontent2
    {
    width:400px;
    }
    /* The Save-button */
    #addnewphrases .zend_form input#Save{
    width:auto;
    }

    ReplyDelete
  40. Fantastic Tutorial on Forms...
    I have just one problem, I am trying to use this in Init function instead of the constructor.

    init is generally the best place to perform all these actions.
    I am getting the labels, but the elements are not created

    Any clue

    ReplyDelete
  41. Awesome article - clearly and well explained, there is no better one around web! Thanks for your effort, it helped me a lot!
    Best regards :)

    ReplyDelete
  42. That is grate article, but I think there is also a method where we can override zend decorator class then we do not have to write long codes.
    If you have this Idea please suggest us.

    ReplyDelete
  43. Your tutorial is great.
    But i can clearly say that using Zend framework is bringing a lot of pain without real benefit. What can i expect to do that for every form and different layout ? Some Zend concepts are good, but there are too many things that simply are done better in some other way.
    Thinking of a self made form framework is far more simpler made by the worst developer.

    ReplyDelete
  44. thanks for this great work. Everyone faces one or two problems every day. Most people find solutions to their problems because very few people share their problems and more or less their solutions. You just help me cross the bridge.

    ReplyDelete
  45. I think Zend_Form is an overkill for a simple task of creating a HTML form especially when you need to customize the design. Hoping to see Zend 2.0 does much better job.

    ReplyDelete
  46. Great comprehensive article on non-comprehensive subject. I though I am nuts before. Thank you!

    ReplyDelete
  47. I found this blog very informative, i want to know something more about name tags and name labels. Thanks for your post, Keep posting such useful information.

    ReplyDelete
  48. This comment has been removed by the author.

    ReplyDelete
  49. great tutorial ;)

    ReplyDelete
  50. Residential painting services are available at affordable prices in London.

    londondecoratorsuk.com

    londondecoratorsuk

    ReplyDelete
  51. Thank you, it really helped.

    ReplyDelete
  52. I have applied the decorators on all the form elements including the form elements like textbox,textarea and submit button using table tag but when i am applying the decorators on the captcha it is not coming in table format.I hope you understand what i am trying to say.. can you please suggest me something....

    ReplyDelete
  53. Kinda like funny comment.. But its a decoration too.. We have another interior decorators in chennai.. ..

    ReplyDelete
  54. very well made tutorial, thanks. I experienced a bit around to understand how things are working. I want as result a first row only with labels, and the next row (s) with the text boxes.
    password username
    textbox textbox


    I tried to add like this:
    $lusername=$this->CreateElement('text','lusername')
    ->setLabel('User Name:');

    $lusername->setDecorators(array(
    'ViewHelper',
    'Description',
    'Errors',
    array(array('data'=>'HtmlTag'), array('tag' => 'td')),
    array('Label', array('tag' => 'td')),
    array(array('row'=>'HtmlTag'),array('tag'=>'tr', 'openOnly'=>true))
    // array(array('row'=>'HtmlTag'),array('tag'=>'tr'))
    ));


    $lpassword=$this->CreateElement('text','lpassword')
    ->setLabel('Password:');

    $lpassword->setDecorators(array(

    'ViewHelper',
    'Description',
    'Errors',
    array(array('data'=>'HtmlTag'), array('tag' => 'td')),
    array('Label', array('tag' => 'td'))
    ));

    How can I get the result, I want?

    ReplyDelete
  55. Thank you so much bro. U did really good job

    ReplyDelete