UnDefined

Jonahlyn's Personal Blog

Creating Elements for Zend Form

| Comments

I’m nearly finished with the form I set out to create using Zend_Form and I’ve only written one blog post about what I’ve learned so far. I want to try to get as much knowlege in writing as I can before it’s gone. I’m starting to find that I am only an “expert” at what I’m presently doing at the time. Everything else I have to re-learn at some point and that’s what I’m hoping blog posts like this will help me do when the time comes. That and it might actually help someone else. Who knows.

When I first got started learning Zend_Form, I really wanted to stop and try to understand more about the different ways to create elements. The more I looked at different resources online and in books, I was seeing different ways of creating and configuring elements. At first this was confusing but I came to see how this made form creation incredibly flexible.

Creating an Element

You can create elements by either instanciating objects or by using the factory method ‘createElement’. When instanciating objects, it’s necessary to know the class name of the type of element you are trying to create. Alternatively, the factory method accepts a string as the first argument that determines what type of element it will create.

The following snippet shows both ways of creating the same text field with an id of ‘fullname’.

The table below lists the class names of some of the more basic types of form controls with the matching string that can be passed to createElement to create the same type of element. These and more are described in some detail in the Zend Programmer’s Reference.

Class NameElement String
Zend_Form_Element_Text text
Zend_Form_Element_Textarea textarea
Zend_Form_Element_Select select
Zend_Form_Element_Radio radio
Zend_Form_Element_Checkbox checkbox
Zend_Form_Element_Hidden hidden
Zend_Form_Element_Reset reset
Zend_Form_Element_Submit submit

Configuring the Element

You can configure an element by setting various properties for it including the label, description, whether or not it is a required field, filters and validators for the input, and decorators that determine how the element will look. I’m not going to describe these in detail because that would make this post too long. What I want to show is that these options can be set either by passing an array of options, by calling methods on the element object, or any combination of the two.

The code snippets below create and configure the exact same element. I think I prefer passing an array of options (the 1st snippet) over calling the individual methods. It just seems cleaner to me.

Thanks for reading!

Comments