Archive for the ‘Zend_Form’ Category
Load custom elements with Zend_Form
My previous post talked about Zend_Plugin_Loader and how to use it in your code. In that post, I also mentioned that Zend_Plugin_Loader is used quite a bit throughout the Zend Framework code. In this post, I’m going to show you how to make use of the plugin loader to load your own custom elements into Zend_Form.
Zend_Form uses factory methods like createElement and addElement in order to simplify adding elements to your form. Using these methods, you can refer to default Zend Form elements by name and they will be instantiated for you and added to your form. For instance, to create a form with text field, your code might look something like this:
1 2 | $form = new Zend_Form; $form->addElement('text', 'user_name'); |
Behind the scenes, Zend_Form is using a plugin loader to look for the “text” element, which will then be instantiated and added to the form. In this case, you would get an instance of Zend_Form_Element_Text. What if you wanted to use your own custom text element instead? Your first instinct might be to do something like this:
1 2 3 | $form = new Zend_Form; $user_name = new My_Form_Element_Text('user_name'); $form->addElement($user_name); |
This works fine, and for small forms is probably the way to go. However, making use of the built in plugin loaders in Zend_Form (I think) leads to a little cleaner and more flexible solution. Here’s what the same example looks like using Zend_Form’s plugin loader:
1 2 3 | $form = new Zend_Form; $form->addPrefixPath("My_Form", "My/Form/"); $form->addElement('text', 'user_name'); |
Your form instance will now look for My_Form_Element_Text first before loading the default Zend_Form elements. This also takes care of setting up the plugin loader for decorators as well. This is nice because you don’t have to change your actual form code beyond adding the new prefix paths. This allows your forms to be much more flexible with respect to what elements and decorators are loaded.
Plugin loaders for element validators, filters, and decorators
One last bit, similar to the form instance itself, each element also has plugin loaders for decorators, filters and validators. Conveniently, you can set the prefix path for all elements added to a form using the Zend_Form::addElementPrefixPath method. This is where you’ll begin to see a lot of the power of Zend_Form, loading custom validators for your elements just as you would any other validator. It’s fun stuff!
Conclusion
You now have a way to load your own custom elements and decorators for forms, and a way to load decorators, filters and validators for your custom (or standard) elements. Enjoy!