1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.form.forms">
4 <title>Creating Forms Using Zend_Form</title>
7 The <classname>Zend_Form</classname> class is used to aggregate form elements,
8 display groups, and subforms. It can then perform the following actions
15 Validation, including retrieving error codes and messages
21 Value aggregation, including populating items and retrieving both
22 filtered and unfiltered values from all items
28 Iteration over all items, in the order in which they are entered or
29 based on the order hints retrieved from each item
35 Rendering of the entire form, either via a single decorator that
36 performs custom rendering or by iterating over each item in the form
42 While forms created with <classname>Zend_Form</classname> may be complex, probably
43 the best use case is for simple forms; its best use is for Rapid
44 Application Development (RAD) and prototyping.
48 At its most basic, you simply instantiate a form object:
51 <programlisting language="php"><![CDATA[
52 // Generic form object:
53 $form = new Zend_Form();
55 // Custom form object:
60 You can optionally pass in a instance of <classname>Zend_Config</classname> or an array,
61 which will be used to set object state and potentially create new elements:
64 <programlisting language="php"><![CDATA[
65 // Passing in configuration options:
66 $form = new Zend_Form($config);
70 <classname>Zend_Form</classname> is iterable, and will iterate over elements,
71 display groups, and subforms, using the order they were registered and
72 any order index each may have. This is useful in cases where you wish to
73 render the elements manually in the appropriate order.
77 <classname>Zend_Form</classname>'s magic lies in its ability to serve as a factory
78 for elements and display groups, as well as the ability to render itself
82 <sect2 id="zend.form.forms.plugins">
83 <title>Plugin Loaders</title>
86 <classname>Zend_Form</classname> makes use of
87 <classname>Zend_Loader_PluginLoader</classname> to allow developers to specify
88 the locations of alternate elements and decorators. Each has its own
89 plugin loader associated with it, and general accessors are used to
90 retrieve and modify each.
94 The following loader types are used with the various plugin loader
95 methods: 'element' and 'decorator'. The type names are case
100 The methods used to interact with plugin loaders are as follows:
106 <methodname>setPluginLoader($loader, $type)</methodname>: $loader is the
107 plugin loader object itself, while type is one of the types
108 specified above. This sets the plugin loader for the given type
109 to the newly specified loader object.
115 <methodname>getPluginLoader($type)</methodname>: retrieves the plugin loader
116 associated with $type.
122 <methodname>addPrefixPath($prefix, $path, $type = null)</methodname>: adds a
123 prefix/path association to the loader specified by $type. If
124 $type is <constant>NULL</constant>, it will attempt to add the path to all
125 loaders, by appending the prefix with each of "_Element" and
126 "_Decorator"; and appending the path with "Element/" and
127 "Decorator/". If you have all your extra form element classes
128 under a common hierarchy, this is a convenience method for
129 setting the base prefix for them.
135 <methodname>addPrefixPaths(array $spec)</methodname>: allows you to add many
136 paths at once to one or more plugin loaders. It expects each
137 array item to be an array with the keys 'path', 'prefix', and
144 Additionally, you can specify prefix paths for all elements and
145 display groups created through a <classname>Zend_Form</classname> instance
146 using the following methods:
152 <methodname>addElementPrefixPath($prefix, $path, $type = null)</methodname>:
153 Just like <methodname>addPrefixPath()</methodname>, you must specify a class
154 prefix and a path. <varname>$type</varname>, when specified, must be
155 one of the plugin loader types specified by
156 <classname>Zend_Form_Element</classname>; see the <link
157 linkend="zend.form.elements.loaders">element plugins
158 section</link> for more information on valid
159 <varname>$type</varname> values. If no <varname>$type</varname> is
160 specified, the method will assume it is a general prefix for all
167 <methodname>addDisplayGroupPrefixPath($prefix, $path)</methodname>:
168 Just like <methodname>addPrefixPath()</methodname>, you must specify a class
169 prefix and a path; however, since display groups only support
170 decorators as plugins, no <varname>$type</varname> is necessary.
176 Custom elements and decorators are an easy way to share
177 functionality between forms and encapsulate custom functionality.
179 linkend="zend.form.elements.loaders.customLabel">Custom Label
180 example</link> in the elements documentation for an example of
181 how custom elements can be used as replacements for standard
186 <sect2 id="zend.form.forms.elements">
187 <title>Elements</title>
190 <classname>Zend_Form</classname> provides several accessors for adding and
191 removing form elements from a form. These can take element object
192 instances or serve as factories for instantiating the element
197 The most basic method for adding an element is
198 <methodname>addElement()</methodname>. This method can take either an object of
199 type <classname>Zend_Form_Element</classname> (or of a class extending
200 <classname>Zend_Form_Element</classname>), or arguments for building a new
201 element -- including the element type, name, and any configuration
209 <programlisting language="php"><![CDATA[
210 // Using an element instance:
211 $element = new Zend_Form_Element_Text('foo');
212 $form->addElement($element);
216 // Creates an element of type Zend_Form_Element_Text with the
218 $form->addElement('text', 'foo');
220 // Pass label option to the element:
221 $form->addElement('text', 'foo', array('label' => 'Foo:'));
225 <title>addElement() Implements Fluent Interface</title>
228 <methodname>addElement()</methodname> implements a fluent interface; that is
229 to say, it returns the <classname>Zend_Form</classname> object, and not
230 the element. This is done to allow you to chain together
231 multiple addElement() methods or other form methods that
232 implement the fluent interface (all setters in <classname>Zend_Form</classname>
233 implement the pattern).
237 If you wish to return the element instead, use
238 <methodname>createElement()</methodname>, which is outlined below. Be aware,
239 however, that <methodname>createElement()</methodname> does not attach the
244 Internally, <methodname>addElement()</methodname> actually uses
245 <methodname>createElement()</methodname> to create the element before
246 attaching it to the form.
251 Once an element has been added to the form, you can retrieve it by
252 name. This can be done either by using the <methodname>getElement()</methodname>
253 method or by using overloading to access the element as an object
257 <programlisting language="php"><![CDATA[
259 $foo = $form->getElement('foo');
261 // As object property:
266 Occasionally, you may want to create an element without attaching it
267 to the form (for instance, if you wish to make use of the various
268 plugin paths registered with the form, but wish to later attach the
269 object to a sub form). The <methodname>createElement()</methodname> method
273 <programlisting language="php"><![CDATA[
274 // $username becomes a Zend_Form_Element_Text object:
275 $username = $form->createElement('text', 'username');
278 <sect3 id="zend.form.forms.elements.values">
279 <title>Populating and Retrieving Values</title>
282 After validating a form, you will typically need to retrieve the
283 values so you can perform other operations, such as updating a
284 database or notifying a web service. You can retrieve all values
285 for all elements using <methodname>getValues()</methodname>;
286 <methodname>getValue($name)</methodname> allows you to retrieve a single
287 element's value by element name:
290 <programlisting language="php"><![CDATA[
292 $values = $form->getValues();
294 // Get only 'foo' element's value:
295 $value = $form->getValue('foo');
299 Sometimes you'll want to populate the form with specified values
300 prior to rendering. This can be done with either the
301 <methodname>setDefaults()</methodname> or <methodname>populate()</methodname>
305 <programlisting language="php"><![CDATA[
306 $form->setDefaults($data);
307 $form->populate($data);
311 On the flip side, you may want to clear a form after populating
312 or validating it; this can be done using the
313 <methodname>reset()</methodname> method:
316 <programlisting language="php"><![CDATA[
321 <sect3 id="zend.form.forms.elements.global">
322 <title>Global Operations</title>
325 Occasionally you will want certain operations to affect all
326 elements. Common scenarios include needing to set plugin prefix
327 paths for all elements, setting decorators for all elements, and
328 setting filters for all elements. As examples:
331 <example id="zend.form.forms.elements.global.allpaths">
332 <title>Setting Prefix Paths for All Elements</title>
335 You can set prefix paths for all elements by type, or using
336 a global prefix. Some examples:
339 <programlisting language="php"><![CDATA[
340 // Set global prefix path:
341 // Creates paths for prefixes My_Foo_Filter, My_Foo_Validate,
342 // and My_Foo_Decorator
343 $form->addElementPrefixPath('My_Foo', 'My/Foo/');
345 // Just filter paths:
346 $form->addElementPrefixPath('My_Foo_Filter',
350 // Just validator paths:
351 $form->addElementPrefixPath('My_Foo_Validate',
355 // Just decorator paths:
356 $form->addElementPrefixPath('My_Foo_Decorator',
362 <example id="zend.form.forms.elements.global.decorators">
363 <title>Setting Decorators for All Elements</title>
366 You can set decorators for all elements.
367 <methodname>setElementDecorators()</methodname> accepts an array of
368 decorators, just like <methodname>setDecorators()</methodname>, and will
369 overwrite any previously set decorators in each element. In
370 this example, we set the decorators to simply a ViewHelper
374 <programlisting language="php"><![CDATA[
375 $form->setElementDecorators(array(
382 <example id="zend.form.forms.elements.global.decoratorsFilter">
383 <title>Setting Decorators for Some Elements</title>
386 You can also set decorators for a subset of elements,
387 either by inclusion or exclusion. The second argument to
388 <methodname>setElementDecorators()</methodname> may be an array of
389 element names; by default, specifying such an array will
390 set the specified decorators on those elements only. You
391 may also pass a third argument, a flag indicating whether
392 this list of elements is for inclusion or exclusion
393 purposes. If the flag is <constant>FALSE</constant>, it will decorate all
394 elements <emphasis>except</emphasis> those in the passed list.
395 As with standard usage of the method, any decorators passed
396 will overwrite any previously set decorators in each
401 In the following snippet, we indicate that we want only the
402 ViewHelper and Label decorators for the 'foo' and 'bar'
406 <programlisting language="php"><![CDATA[
407 $form->setElementDecorators(
420 On the flip side, with this snippet, we'll now indicate
421 that we want to use only the ViewHelper and Label
422 decorators for every element <emphasis>except</emphasis>
423 the 'foo' and 'bar' elements:
426 <programlisting language="php"><![CDATA[
427 $form->setElementDecorators(
442 <title>Some Decorators are Inappropriate for Some Elements</title>
445 While <methodname>setElementDecorators()</methodname> may seem like
446 a good solution, there are some cases where it may
447 actually end up with unexpected results. For example,
448 the various button elements (Submit, Button, Reset)
449 currently use the label as the value of the button,
450 and only use ViewHelper and DtDdWrapper decorators --
451 preventing an additional labels, errors, and hints from
452 being rendered. The example above would duplicate some
453 content (the label) for button elements.
457 You can use the inclusion/exclusion array to overcome
458 this issue as noted in the previous example.
462 So, use this method wisely, and realize that you may
463 need to exclude some elements or manually change some elements' decorators
464 to prevent unwanted output.
468 <example id="zend.form.forms.elements.global.filters">
469 <title>Setting Filters for All Elements</title>
472 In some cases, you may want to apply the same filter to all
473 elements; a common case is to <methodname>trim()</methodname> all values:
476 <programlisting language="php"><![CDATA[
477 $form->setElementFilters(array('StringTrim'));
482 <sect3 id="zend.form.forms.elements.methods">
483 <title>Methods For Interacting With Elements</title>
486 The following methods may be used to interact with elements:
492 <methodname>createElement($element, $name = null, $options =
499 <methodname>addElement($element, $name = null, $options = null)</methodname>
505 <methodname>addElements(array $elements)</methodname>
511 <methodname>setElements(array $elements)</methodname>
517 <methodname>getElement($name)</methodname>
523 <methodname>getElements()</methodname>
529 <methodname>removeElement($name)</methodname>
535 <methodname>clearElements()</methodname>
541 <methodname>setDefaults(array $defaults)</methodname>
547 <methodname>setDefault($name, $value)</methodname>
553 <methodname>getValue($name)</methodname>
559 <methodname>getValues()</methodname>
565 <methodname>getUnfilteredValue($name)</methodname>
571 <methodname>getUnfilteredValues()</methodname>
577 <methodname>setElementFilters(array $filters)</methodname>
583 <methodname>setElementDecorators(array $decorators)</methodname>
589 <methodname>addElementPrefixPath($prefix, $path, $type = null)</methodname>
595 <methodname>addElementPrefixPaths(array $spec)</methodname>
602 <sect2 id="zend.form.forms.displaygroups">
603 <title>Display Groups</title>
606 Display groups are a way to create virtual groupings of elements for
607 display purposes. All elements remain accessible by name in the
608 form, but when iterating over the form or rendering, any elements in
609 a display group are rendered together. The most common use case for
610 this is for grouping elements in fieldsets.
614 The base class for display groups is
615 <classname>Zend_Form_DisplayGroup</classname>. While it can be instantiated
616 directly, it is usually best to use <classname>Zend_Form</classname>'s
617 <methodname>addDisplayGroup()</methodname> method to do so. This method takes an
618 array of elements as its first argument, and a name for the display
619 group as its second argument. You may optionally pass in an array of
620 options or a <classname>Zend_Config</classname> object as the third argument.
624 Assuming that the elements 'username' and 'password' are already set
625 in the form, the following code would group these elements in a
626 'login' display group:
629 <programlisting language="php"><![CDATA[
630 $form->addDisplayGroup(array('username', 'password'), 'login');
634 You can access display groups using the
635 <methodname>getDisplayGroup()</methodname> method, or via overloading using the
636 display group's name:
639 <programlisting language="php"><![CDATA[
640 // Using getDisplayGroup():
641 $login = $form->getDisplayGroup('login');
643 // Using overloading:
644 $login = $form->login;
648 <title>Default Decorators Do Not Need to Be Loaded</title>
651 By default, the default decorators are loaded during object
652 initialization. You can disable this by passing the
653 'disableLoadDefaultDecorators' option when creating a display
657 <programlisting language="php"><![CDATA[
658 $form->addDisplayGroup(
661 array('disableLoadDefaultDecorators' => true)
666 This option may be mixed with any other options you pass,
667 both as array options or in a <classname>Zend_Config</classname> object.
671 <sect3 id="zend.form.forms.displaygroups.global">
672 <title>Global Operations</title>
675 Just as with elements, there are some operations which might
676 affect all display groups; these include setting decorators and
677 setting the plugin path in which to look for decorators.
680 <example id="zend.form.forms.displaygroups.global.paths">
681 <title>Setting Decorator Prefix Path for All Display Groups</title>
684 By default, display groups inherit whichever decorator paths
685 the form uses; however, if they should look in alternate
686 locations, you can use the
687 <methodname>addDisplayGroupPrefixPath()</methodname> method.
690 <programlisting language="php"><![CDATA[
691 $form->addDisplayGroupPrefixPath('My_Foo_Decorator', 'My/Foo/Decorator');
695 <example id="zend.form.forms.displaygroups.global.decorators">
696 <title>Setting Decorators for All Display Groups</title>
699 You can set decorators for all display groups.
700 <methodname>setDisplayGroupDecorators()</methodname> accepts an array of
701 decorators, just like <methodname>setDecorators()</methodname>, and will
702 overwrite any previously set decorators in each display
703 group. In this example, we set the decorators to simply a
704 fieldset (the FormElements decorator is necessary to ensure
705 that the elements are iterated):
708 <programlisting language="php"><![CDATA[
709 $form->setDisplayGroupDecorators(array(
717 <sect3 id="zend.form.forms.displaygroups.customClasses">
718 <title>Using Custom Display Group Classes</title>
721 By default, <classname>Zend_Form</classname> uses the
722 <classname>Zend_Form_DisplayGroup</classname> class for display groups.
723 You may find you need to extend this class in order to provided
724 custom functionality. <methodname>addDisplayGroup()</methodname> does not
725 allow passing in a concrete instance, but does allow specifying
726 the class to use as one of its options, using the
727 'displayGroupClass' key:
730 <programlisting language="php"><![CDATA[
731 // Use the 'My_DisplayGroup' class
732 $form->addDisplayGroup(
733 array('username', 'password'),
735 array('displayGroupClass' => 'My_DisplayGroup')
740 If the class has not yet been loaded, <classname>Zend_Form</classname>
741 will attempt to do so using <classname>Zend_Loader</classname>.
745 You can also specify a default display group class to use with
746 the form such that all display groups created with the form
747 object will use that class:
750 <programlisting language="php"><![CDATA[
751 // Use the 'My_DisplayGroup' class for all display groups:
752 $form->setDefaultDisplayGroupClass('My_DisplayGroup');
756 This setting may be specified in configurations as
757 'defaultDisplayGroupClass', and will be loaded early to ensure
758 all display groups use that class.
762 <sect3 id="zend.form.forms.displaygroups.interactionmethods">
763 <title>Methods for Interacting With Display Groups</title>
766 The following methods may be used to interact with display
773 <methodname>addDisplayGroup(array $elements, $name, $options
780 <methodname>addDisplayGroups(array $groups)</methodname>
786 <methodname>setDisplayGroups(array $groups)</methodname>
792 <methodname>getDisplayGroup($name)</methodname>
798 <methodname>getDisplayGroups()</methodname>
804 <methodname>removeDisplayGroup($name)</methodname>
810 <methodname>clearDisplayGroups()</methodname>
816 <methodname>setDisplayGroupDecorators(array $decorators)</methodname>
822 <methodname>addDisplayGroupPrefixPath($prefix, $path)</methodname>
828 <methodname>setDefaultDisplayGroupClass($class)</methodname>
834 <methodname>getDefaultDisplayGroupClass($class)</methodname>
840 <sect3 id="zend.form.forms.displaygroups.methods">
841 <title>Zend_Form_DisplayGroup Methods</title>
844 <classname>Zend_Form_DisplayGroup</classname> has the following methods,
850 <para>Configuration:</para>
855 <methodname>setOptions(array $options)</methodname>
860 <para><methodname>setConfig(Zend_Config $config)</methodname></para>
866 <para>Metadata:</para>
870 <para><methodname>setAttrib($key, $value)</methodname></para>
874 <para><methodname>addAttribs(array $attribs)</methodname></para>
878 <para><methodname>setAttribs(array $attribs)</methodname></para>
881 <listitem><para><methodname>getAttrib($key)</methodname></para></listitem>
882 <listitem><para><methodname>getAttribs()</methodname></para></listitem>
885 <para><methodname>removeAttrib($key)</methodname></para>
888 <listitem><para><methodname>clearAttribs()</methodname></para></listitem>
889 <listitem><para><methodname>setName($name)</methodname></para></listitem>
890 <listitem><para><methodname>getName()</methodname></para></listitem>
893 <para><methodname>setDescription($value)</methodname></para>
896 <listitem><para><methodname>getDescription()</methodname></para></listitem>
899 <para><methodname>setLegend($legend)</methodname></para>
902 <listitem><para><methodname>getLegend()</methodname></para></listitem>
903 <listitem><para><methodname>setOrder($order)</methodname></para></listitem>
904 <listitem><para><methodname>getOrder()</methodname></para></listitem>
909 <para>Elements:</para>
914 <methodname>createElement($type, $name, array $options
915 = array())</methodname>
921 <methodname>addElement($typeOrElement, $name, array $options =
922 array())</methodname>
927 <para><methodname>addElements(array $elements)</methodname></para>
931 <para><methodname>setElements(array $elements)</methodname></para>
934 <listitem><para><methodname>getElement($name)</methodname></para></listitem>
935 <listitem><para><methodname>getElements()</methodname></para></listitem>
938 <para><methodname>removeElement($name)</methodname></para>
941 <listitem><para><methodname>clearElements()</methodname></para></listitem>
946 <para>Plugin loaders:</para>
951 <methodname>setPluginLoader(Zend_Loader_PluginLoader
952 $loader)</methodname>
956 <listitem><para><methodname>getPluginLoader()</methodname></para></listitem>
959 <para><methodname>addPrefixPath($prefix, $path)</methodname></para>
963 <para><methodname>addPrefixPaths(array $spec)</methodname></para>
969 <para>Decorators:</para>
974 <methodname>addDecorator($decorator, $options = null)</methodname>
979 <para><methodname>addDecorators(array $decorators)</methodname></para>
983 <para><methodname>setDecorators(array $decorators)</methodname></para>
987 <para><methodname>getDecorator($name)</methodname></para>
990 <listitem><para><methodname>getDecorators()</methodname></para></listitem>
993 <para><methodname>removeDecorator($name)</methodname></para>
996 <listitem><para><methodname>clearDecorators()</methodname></para></listitem>
1001 <para>Rendering:</para>
1006 <methodname>setView(Zend_View_Interface $view = null)</methodname>
1010 <listitem><para><methodname>getView()</methodname></para></listitem>
1014 <methodname>render(Zend_View_Interface $view = null)</methodname>
1026 <methodname>setTranslator(Zend_Translate_Adapter $translator =
1031 <listitem><para><methodname>getTranslator()</methodname></para></listitem>
1034 <para><methodname>setDisableTranslator($flag)</methodname></para>
1038 <para><methodname>translatorIsDisabled()</methodname></para>
1046 <sect2 id="zend.form.forms.subforms">
1047 <title>Sub Forms</title>
1050 Sub forms serve several purposes:
1056 Creating logical element groups. Since sub forms are simply
1057 forms, you can validate subforms as individual entities.
1063 Creating multi-page forms. Since sub forms are simply forms, you
1064 can display a separate sub form per page, building up multi-page
1065 forms where each form has its own validation logic. Only once
1066 all sub forms validate would the form be considered complete.
1072 Display groupings. Like display groups, sub forms, when rendered
1073 as part of a larger form, can be used to group elements. Be
1074 aware, however, that the master form object will have no
1075 awareness of the elements in sub forms.
1081 A sub form may be a <classname>Zend_Form</classname> object, or, more
1082 typically, a <classname>Zend_Form_SubForm</classname> object. The latter
1083 contains decorators suitable for inclusion in a larger form (i.e.,
1084 it does not render additional HTML form tags, but does group
1085 elements). To attach a sub form, simply add it to the form and give
1089 <programlisting language="php"><![CDATA[
1090 $form->addSubForm($subForm, 'subform');
1091 ]]></programlisting>
1094 You can retrieve a sub form using either
1095 <methodname>getSubForm($name)</methodname> or overloading using the sub form
1099 <programlisting language="php"><![CDATA[
1100 // Using getSubForm():
1101 $subForm = $form->getSubForm('subform');
1103 // Using overloading:
1104 $subForm = $form->subform;
1105 ]]></programlisting>
1108 Sub forms are included in form iteration, although the elements they
1112 <sect3 id="zend.form.forms.subforms.global">
1113 <title>Global Operations</title>
1116 Like elements and display groups, there are some operations that
1117 might need to affect all sub forms. Unlike display groups and
1118 elements, however, sub forms inherit most functionality from the
1119 master form object, and the only real operation that may need to
1120 be performed globally is setting decorators for sub forms. For
1121 this purpose, there is the <methodname>setSubFormDecorators()</methodname>
1122 method. In the next example, we'll set the decorator for all
1123 subforms to be simply a fieldset (the FormElements decorator is
1124 needed to ensure its elements are iterated):
1127 <programlisting language="php"><![CDATA[
1128 $form->setSubFormDecorators(array(
1132 ]]></programlisting>
1135 <sect3 id="zend.form.forms.subforms.methods">
1136 <title>Methods for Interacting With Sub Forms</title>
1139 The following methods may be used to interact with sub forms:
1145 <methodname>addSubForm(Zend_Form $form, $name, $order = null)</methodname>
1151 <methodname>addSubForms(array $subForms)</methodname>
1157 <methodname>setSubForms(array $subForms)</methodname>
1163 <methodname>getSubForm($name)</methodname>
1169 <methodname>getSubForms()</methodname>
1175 <methodname>removeSubForm($name)</methodname>
1181 <methodname>clearSubForms()</methodname>
1187 <methodname>setSubFormDecorators(array $decorators)</methodname>
1194 <sect2 id="zend.form.forms.metadata">
1195 <title>Metadata and Attributes</title>
1198 While a form's usefulness primarily derives from the elements it
1199 contains, it can also contain other metadata, such as a name (often
1200 used as a unique ID in the HTML markup); the form action and method;
1201 the number of elements, groups, and sub forms it contains; and
1202 arbitrary metadata (usually used to set HTML attributes for the form
1207 You can set and retrieve a form's name using the name accessors:
1210 <programlisting language="php"><![CDATA[
1212 $form->setName('registration');
1214 // Retrieve the name:
1215 $name = $form->getName();
1216 ]]></programlisting>
1219 To set the action (url to which the form submits) and method (method
1220 by which it should submit, e.g., 'POST' or 'GET'), use the action
1221 and method accessors:
1224 <programlisting language="php"><![CDATA[
1225 // Set the action and method:
1226 $form->setAction('/user/login')
1227 ->setMethod('post');
1228 ]]></programlisting>
1231 You may also specify the form encoding type specifically using the
1232 enctype accessors. <classname>Zend_Form</classname> defines two constants,
1233 <constant>Zend_Form::ENCTYPE_URLENCODED</constant> and
1234 <constant>Zend_Form::ENCTYPE_MULTIPART</constant>, corresponding to the
1235 values 'application/x-www-form-urlencoded' and
1236 'multipart/form-data', respectively; however, you can set this to
1237 any arbitrary encoding type.
1240 <programlisting language="php"><![CDATA[
1241 // Set the action, method, and enctype:
1242 $form->setAction('/user/login')
1244 ->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
1245 ]]></programlisting>
1249 The method, action, and enctype are only used internally for rendering,
1250 and not for any sort of validation.
1255 <classname>Zend_Form</classname> implements the <classname>Countable</classname>
1256 interface, allowing you to pass it as an argument to count:
1259 <programlisting language="php"><![CDATA[
1260 $numItems = count($form);
1261 ]]></programlisting>
1264 Setting arbitrary metadata is done through the attribs accessors.
1265 Since overloading in <classname>Zend_Form</classname> is used to access
1266 elements, display groups, and sub forms, this is the only method for
1270 <programlisting language="php"><![CDATA[
1271 // Setting attributes:
1272 $form->setAttrib('class', 'zend-form')
1274 'id' => 'registration',
1275 'onSubmit' => 'validate(this)',
1278 // Retrieving attributes:
1279 $class = $form->getAttrib('class');
1280 $attribs = $form->getAttribs();
1282 // Remove an attribute:
1283 $form->removeAttrib('onSubmit');
1285 // Clear all attributes:
1286 $form->clearAttribs();
1287 ]]></programlisting>
1290 <sect2 id="zend.form.forms.decorators">
1291 <title>Decorators</title>
1294 Creating the markup for a form is often a time-consuming task,
1295 particularly if you plan on re-using the same markup to show things
1296 such as validation errors, submitted values, etc.
1297 <classname>Zend_Form</classname>'s answer to this issue is
1298 <emphasis>decorators</emphasis>.
1302 Decorators for <classname>Zend_Form</classname> objects can be used to render
1303 a form. The FormElements decorator will iterate through all items in
1304 a form -- elements, display groups, and sub forms -- and render
1305 them, returning the result. Additional decorators may then be used
1306 to wrap this content, or append or prepend it.
1310 The default decorators for <classname>Zend_Form</classname> are FormElements,
1311 HtmlTag (wraps in a definition list), and Form; the equivalent code
1312 for creating them is as follows:
1315 <programlisting language="php"><![CDATA[
1316 $form->setDecorators(array(
1318 array('HtmlTag', array('tag' => 'dl')),
1321 ]]></programlisting>
1324 This creates output like the following:
1327 <programlisting language="html"><![CDATA[
1328 <form action="/form/action" method="post">
1333 ]]></programlisting>
1336 Any attributes set on the form object will be used as HTML
1337 attributes of the <emphasis><form></emphasis> tag.
1341 <title>Default Decorators Do Not Need to Be Loaded</title>
1344 By default, the default decorators are loaded during object
1345 initialization. You can disable this by passing the
1346 'disableLoadDefaultDecorators' option to the constructor:
1349 <programlisting language="php"><![CDATA[
1350 $form = new Zend_Form(array('disableLoadDefaultDecorators' => true));
1351 ]]></programlisting>
1354 This option may be mixed with any other options you pass,
1355 both as array options or in a <classname>Zend_Config</classname> object.
1360 <title>Using Multiple Decorators of the Same Type</title>
1363 Internally, <classname>Zend_Form</classname> uses a decorator's
1364 class as the lookup mechanism when retrieving decorators. As a
1365 result, you cannot register multiple decorators of the same
1366 type; subsequent decorators will simply overwrite those that
1371 To get around this, you can use aliases. Instead of passing a
1372 decorator or decorator name as the first argument to
1373 <methodname>addDecorator()</methodname>, pass an array with a single
1374 element, with the alias pointing to the decorator object or
1378 <programlisting language="php"><![CDATA[
1379 // Alias to 'FooBar':
1380 $form->addDecorator(array('FooBar' => 'HtmlTag'), array('tag' => 'div'));
1382 // And retrieve later:
1383 $form = $element->getDecorator('FooBar');
1384 ]]></programlisting>
1387 In the <methodname>addDecorators()</methodname> and
1388 <methodname>setDecorators()</methodname> methods, you will need to pass
1389 the 'decorator' option in the array representing the decorator:
1392 <programlisting language="php"><![CDATA[
1393 // Add two 'HtmlTag' decorators, aliasing one to 'FooBar':
1394 $form->addDecorators(
1395 array('HtmlTag', array('tag' => 'div')),
1397 'decorator' => array('FooBar' => 'HtmlTag'),
1398 'options' => array('tag' => 'dd')
1402 // And retrieve later:
1403 $htmlTag = $form->getDecorator('HtmlTag');
1404 $fooBar = $form->getDecorator('FooBar');
1405 ]]></programlisting>
1409 You may create your own decorators for generating the form. One
1410 common use case is if you know the exact HTML you wish to use; your
1411 decorator could create the exact HTML and simply return it,
1412 potentially using the decorators from individual elements or display
1417 The following methods may be used to interact with decorators:
1423 <methodname>addDecorator($decorator, $options = null)</methodname>
1429 <methodname>addDecorators(array $decorators)</methodname>
1435 <methodname>setDecorators(array $decorators)</methodname>
1441 <methodname>getDecorator($name)</methodname>
1447 <methodname>getDecorators()</methodname>
1453 <methodname>removeDecorator($name)</methodname>
1459 <methodname>clearDecorators()</methodname>
1465 <classname>Zend_Form</classname> also uses overloading to allow rendering
1466 specific decorators. <methodname>__call()</methodname> will intercept methods
1467 that lead with the text 'render' and use the remainder of the method
1468 name to lookup a decorator; if found, it will then render that
1469 <emphasis>single</emphasis> decorator. Any arguments passed to the
1470 method call will be used as content to pass to the decorator's
1471 <methodname>render()</methodname> method. As an example:
1474 <programlisting language="php"><![CDATA[
1475 // Render only the FormElements decorator:
1476 echo $form->renderFormElements();
1478 // Render only the fieldset decorator, passing in content:
1479 echo $form->renderFieldset("<p>This is fieldset content</p>");
1480 ]]></programlisting>
1483 If the decorator does not exist, an exception is raised.
1487 <sect2 id="zend.form.forms.validation">
1488 <title>Validation</title>
1491 A primary use case for forms is validating submitted data.
1492 <classname>Zend_Form</classname> allows you to validate an entire form, a partial form,
1493 or responses for XmlHttpRequests (AJAX). If the submitted data is not valid, it has
1494 methods for retrieving the various error codes and messages for
1495 elements and sub forms.
1499 To validate a full form, use the <methodname>isValid()</methodname> method:
1502 <programlisting language="php"><![CDATA[
1503 if (!$form->isValid($_POST)) {
1504 // failed validation
1506 ]]></programlisting>
1509 <methodname>isValid()</methodname> will validate every required element, and any
1510 unrequired element contained in the submitted data.
1514 Sometimes you may need to validate only a subset of the data; for
1515 this, use <methodname>isValidPartial($data)</methodname>:
1518 <programlisting language="php"><![CDATA[
1519 if (!$form->isValidPartial($data)) {
1520 // failed validation
1522 ]]></programlisting>
1525 <methodname>isValidPartial()</methodname> only attempts to validate those items
1526 in the data for which there are matching elements; if an element is
1527 not represented in the data, it is skipped.
1531 When validating elements or groups of elements for an <acronym>AJAX</acronym> request,
1532 you will typically be validating a subset of the form, and want the
1533 response back in <acronym>JSON</acronym>. <methodname>processAjax()</methodname> does
1537 <programlisting language="php"><![CDATA[
1538 $json = $form->processAjax($data);
1539 ]]></programlisting>
1542 You can then simply send the <acronym>JSON</acronym> response to the client. If the
1543 form is valid, this will be a boolean <constant>TRUE</constant> response. If not, it
1544 will be a javascript object containing key/message pairs, where each
1545 'message' is an array of validation error messages.
1549 For forms that fail validation, you can retrieve both error codes
1550 and error messages, using <methodname>getErrors()</methodname> and
1551 <methodname>getMessages()</methodname>, respectively:
1554 <programlisting language="php"><![CDATA[
1555 $codes = $form->getErrors();
1556 $messages = $form->getMessages();
1557 ]]></programlisting>
1561 Since the messages returned by <methodname>getMessages()</methodname> are an
1562 array of error code/message pairs, <methodname>getErrors()</methodname> is
1563 typically not needed.
1568 You can retrieve codes and error messages for individual elements by
1569 simply passing the element name to each:
1572 <programlisting language="php"><![CDATA[
1573 $codes = $form->getErrors('username');
1574 $messages = $form->getMessages('username');
1575 ]]></programlisting>
1579 Note: When validating elements, <classname>Zend_Form</classname> sends a
1580 second argument to each element's <methodname>isValid()</methodname> method:
1581 the array of data being validated. This can then be used by
1582 individual validators to allow them to utilize other submitted
1583 values when determining the validity of the data. An example
1584 would be a registration form that requires both a password and
1585 password confirmation; the password element could use the
1586 password confirmation as part of its validation.
1590 <sect3 id="zend.form.forms.validation.errors">
1591 <title>Custom Error Messages</title>
1594 At times, you may want to specify one or more specific error
1595 messages to use instead of the error messages generated by the
1596 validators attached to your elements. Additionally, at times you
1597 may want to mark the form invalid yourself. This
1598 functionality is possible via the following methods.
1604 <methodname>addErrorMessage($message)</methodname>: add an error message
1605 to display on form validation errors. You may call this more
1606 than once, and new messages are appended to the stack.
1612 <methodname>addErrorMessages(array $messages)</methodname>: add multiple
1613 error messages to display on form validation errors.
1619 <methodname>setErrorMessages(array $messages)</methodname>: add multiple
1620 error messages to display on form validation errors,
1621 overwriting all previously set error messages.
1627 <methodname>getErrorMessages()</methodname>: retrieve the list of
1628 custom error messages that have been defined.
1634 <methodname>clearErrorMessages()</methodname>: remove all custom error
1635 messages that have been defined.
1641 <methodname>markAsError()</methodname>: mark the form as having
1648 <methodname>addError($message)</methodname>: add a message to the custom
1649 error messages stack and flag the form as invalid.
1655 <methodname>addErrors(array $messages)</methodname>: add several
1656 messages to the custom error messages stack and flag the
1663 <methodname>setErrors(array $messages)</methodname>: overwrite the
1664 custom error messages stack with the provided messages and
1665 flag the form as invalid.
1671 All errors set in this fashion may be translated.
1675 <sect3 id="zend.form.forms.validation.values">
1676 <title>Retrieving Valid Values Only</title>
1679 There are scenarios when you want to allow your user to work on a valid form
1680 in several steps. Meanwhile you allow the user to save the form with any
1681 set of values inbetween. Then if all the data is specified you can transfer
1682 the model from the building or prototying stage to a valid stage.
1686 You can retrieve all the valid values that match the submitted data by calling:
1689 <programlisting language="php"><![CDATA[
1690 $validValues = $form->getValidValues($_POST);
1691 ]]></programlisting>
1695 <sect2 id="zend.form.forms.methods">
1696 <title>Methods</title>
1699 The following is a full list of methods available to
1700 <classname>Zend_Form</classname>, grouped by type:
1705 <para>Configuration and Options:</para>
1709 <para><methodname>setOptions(array $options)</methodname></para>
1713 <para><methodname>setConfig(Zend_Config $config)</methodname></para>
1719 <para>Plugin Loaders and paths:</para>
1724 <methodname>setPluginLoader(Zend_Loader_PluginLoader_Interface $loader,
1725 $type = null)</methodname>
1730 <para><methodname>getPluginLoader($type = null)</methodname></para>
1735 <methodname>addPrefixPath($prefix, $path, $type = null) </methodname>
1740 <para><methodname>addPrefixPaths(array $spec)</methodname></para>
1745 <methodname>addElementPrefixPath($prefix, $path, $type
1746 = null)</methodname>
1751 <para><methodname>addElementPrefixPaths(array $spec)</methodname></para>
1756 <methodname>addDisplayGroupPrefixPath($prefix, $path)</methodname>
1763 <para>Metadata:</para>
1767 <para><methodname>setAttrib($key, $value)</methodname></para>
1771 <para><methodname>addAttribs(array $attribs)</methodname></para>
1775 <para><methodname>setAttribs(array $attribs)</methodname></para>
1778 <listitem><para><methodname>getAttrib($key)</methodname></para></listitem>
1779 <listitem><para><methodname>getAttribs()</methodname></para></listitem>
1780 <listitem><para><methodname>removeAttrib($key)</methodname></para></listitem>
1781 <listitem><para><methodname>clearAttribs()</methodname></para></listitem>
1782 <listitem><para><methodname>setAction($action)</methodname></para></listitem>
1783 <listitem><para><methodname>getAction()</methodname></para></listitem>
1784 <listitem><para><methodname>setMethod($method)</methodname></para></listitem>
1785 <listitem><para><methodname>getMethod()</methodname></para></listitem>
1786 <listitem><para><methodname>setName($name)</methodname></para></listitem>
1787 <listitem><para><methodname>getName()</methodname></para></listitem>
1792 <para>Elements:</para>
1797 <methodname>addElement($element, $name = null, $options
1798 = null)</methodname>
1803 <para><methodname>addElements(array $elements)</methodname></para>
1807 <para><methodname>setElements(array $elements)</methodname></para>
1810 <listitem><para><methodname>getElement($name)</methodname></para></listitem>
1811 <listitem><para><methodname>getElements()</methodname></para></listitem>
1812 <listitem><para><methodname>removeElement($name)</methodname></para></listitem>
1813 <listitem><para><methodname>clearElements()</methodname></para></listitem>
1816 <para><methodname>setDefaults(array $defaults)</methodname></para>
1820 <para><methodname>setDefault($name, $value)</methodname></para>
1823 <listitem><para><methodname>getValue($name)</methodname></para></listitem>
1824 <listitem><para><methodname>getValues()</methodname></para></listitem>
1827 <para><methodname>getUnfilteredValue($name)</methodname></para>
1830 <listitem><para><methodname>getUnfilteredValues()</methodname></para></listitem>
1833 <para><methodname>setElementFilters(array $filters)</methodname></para>
1838 <methodname>setElementDecorators(array $decorators)</methodname>
1845 <para>Sub forms:</para>
1850 <methodname>addSubForm(Zend_Form $form, $name, $order
1851 = null)</methodname>
1856 <para><methodname>addSubForms(array $subForms)</methodname></para>
1860 <para><methodname>setSubForms(array $subForms)</methodname></para>
1863 <listitem><para><methodname>getSubForm($name)</methodname></para></listitem>
1864 <listitem><para><methodname>getSubForms()</methodname></para></listitem>
1865 <listitem><para><methodname>removeSubForm($name)</methodname></para></listitem>
1866 <listitem><para><methodname>clearSubForms()</methodname></para></listitem>
1870 <methodname>setSubFormDecorators(array $decorators)</methodname>
1877 <para>Display groups:</para>
1882 <methodname>addDisplayGroup(array $elements, $name, $options
1883 = null)</methodname>
1888 <para><methodname>addDisplayGroups(array $groups)</methodname></para>
1892 <para><methodname>setDisplayGroups(array $groups)</methodname></para>
1896 <para><methodname>getDisplayGroup($name)</methodname></para>
1899 <listitem><para><methodname>getDisplayGroups()</methodname></para></listitem>
1902 <para><methodname>removeDisplayGroup($name)</methodname></para>
1905 <listitem><para><methodname>clearDisplayGroups()</methodname></para></listitem>
1909 <methodname>setDisplayGroupDecorators(array $decorators)</methodname>
1916 <para>Validation</para>
1920 <para><methodname>populate(array $values)</methodname></para>
1923 <listitem><para><methodname>isValid(array $data)</methodname></para></listitem>
1926 <para><methodname>isValidPartial(array $data)</methodname></para>
1930 <para><methodname>processAjax(array $data)</methodname></para>
1933 <listitem><para><methodname>persistData()</methodname></para></listitem>
1936 <para><methodname>getErrors($name = null)</methodname></para>
1940 <para><methodname>getMessages($name = null)</methodname></para>
1946 <para>Rendering:</para>
1951 <methodname>setView(Zend_View_Interface $view = null)</methodname>
1955 <listitem><para><methodname>getView()</methodname></para></listitem>
1959 <methodname>addDecorator($decorator, $options = null)</methodname>
1964 <para><methodname>addDecorators(array $decorators)</methodname></para>
1968 <para><methodname>setDecorators(array $decorators)</methodname></para>
1971 <listitem><para><methodname>getDecorator($name)</methodname></para></listitem>
1972 <listitem><para><methodname>getDecorators()</methodname></para></listitem>
1975 <para><methodname>removeDecorator($name)</methodname></para>
1978 <listitem><para><methodname>clearDecorators()</methodname></para></listitem>
1982 <methodname>render(Zend_View_Interface $view = null)</methodname>
1994 <methodname>setTranslator(Zend_Translate_Adapter $translator
1995 = null)</methodname>
1999 <listitem><para><methodname>getTranslator()</methodname></para></listitem>
2002 <para><methodname>setDisableTranslator($flag)</methodname></para>
2006 <para><methodname>translatorIsDisabled()</methodname></para>
2013 <sect2 id="zend.form.forms.config">
2014 <title>Configuration</title>
2017 <classname>Zend_Form</classname> is fully configurable via
2018 <methodname>setOptions()</methodname> and <methodname>setConfig()</methodname> (or by
2019 passing options or a <classname>Zend_Config</classname> object to the
2020 constructor). Using these methods, you can specify form elements,
2021 display groups, decorators, and metadata.
2025 As a general rule, if 'set' + the option key refers to a
2026 <classname>Zend_Form</classname> method, then the value provided will be
2027 passed to that method. If the accessor does not exist, the key is
2028 assumed to reference an attribute, and will be passed to
2029 <methodname>setAttrib()</methodname>.
2033 Exceptions to the rule include the following:
2039 <property>prefixPaths</property> will be passed to
2040 <methodname>addPrefixPaths()</methodname>
2046 <property>elementPrefixPaths</property> will be passed to
2047 <methodname>addElementPrefixPaths()</methodname>
2053 <property>displayGroupPrefixPaths</property> will be passed to
2054 <methodname>addDisplayGroupPrefixPaths()</methodname>
2059 <para>the following setters cannot be set in this way:</para>
2063 <para><property>setAttrib</property> (though setAttribs *will* work)</para>
2066 <listitem><para><property>setConfig</property></para></listitem>
2067 <listitem><para><property>setDefault</property></para></listitem>
2068 <listitem><para><property>setOptions</property></para></listitem>
2069 <listitem><para><property>setPluginLoader</property></para></listitem>
2070 <listitem><para><property>setSubForms</property></para></listitem>
2071 <listitem><para><property>setTranslator</property></para></listitem>
2072 <listitem><para><property>setView</property></para></listitem>
2078 As an example, here is a config file that passes configuration for
2079 every type of configurable data:
2082 <programlisting language="ini"><![CDATA[
2084 name = "registration"
2085 action = "/user/register"
2087 attribs.class = "zend_form"
2088 attribs.onclick = "validate(this)"
2090 disableTranslator = 0
2092 prefixPath.element.prefix = "My_Element"
2093 prefixPath.element.path = "My/Element/"
2094 elementPrefixPath.validate.prefix = "My_Validate"
2095 elementPrefixPath.validate.path = "My/Validate/"
2096 displayGroupPrefixPath.prefix = "My_Group"
2097 displayGroupPrefixPath.path = "My/Group/"
2099 elements.username.type = "text"
2100 elements.username.options.label = "Username"
2101 elements.username.options.validators.alpha.validator = "Alpha"
2102 elements.username.options.filters.lcase = "StringToLower"
2103 ; more elements, of course...
2105 elementFilters.trim = "StringTrim"
2106 ;elementDecorators.trim = "StringTrim"
2108 displayGroups.login.elements.username = "username"
2109 displayGroups.login.elements.password = "password"
2110 displayGroupDecorators.elements.decorator = "FormElements"
2111 displayGroupDecorators.fieldset.decorator = "Fieldset"
2113 decorators.elements.decorator = "FormElements"
2114 decorators.fieldset.decorator = "FieldSet"
2115 decorators.fieldset.decorator.options.class = "zend_form"
2116 decorators.form.decorator = "Form"
2117 ]]></programlisting>
2120 The above could easily be abstracted to an <acronym>XML</acronym> or
2121 <acronym>PHP</acronym> array-based configuration file.
2125 <sect2 id="zend.form.forms.custom">
2126 <title>Custom forms</title>
2129 An alternative to using configuration-based forms is to subclass
2130 <classname>Zend_Form</classname>. This has several benefits:
2136 You can unit test your form easily to ensure validations and
2137 rendering perform as expected.
2143 Fine-grained control over individual elements.
2149 Re-use of form objects, and greater portability (no need to
2150 track config files).
2156 Implementing custom functionality.
2162 The most typical use case would be to use the
2163 <methodname>init()</methodname> method to setup specific form elements and
2167 <programlisting language="php"><![CDATA[
2168 class My_Form_Login extends Zend_Form
2170 public function init()
2172 $username = new Zend_Form_Element_Text('username');
2173 $username->class = 'formtext';
2174 $username->setLabel('Username:')
2175 ->setDecorators(array(
2177 array('helper' => 'formText')),
2179 array('class' => 'label'))
2182 $password = new Zend_Form_Element_Password('password');
2183 $password->class = 'formtext';
2184 $password->setLabel('Username:')
2185 ->setDecorators(array(
2187 array('helper' => 'formPassword')),
2189 array('class' => 'label'))
2192 $submit = new Zend_Form_Element_Submit('login');
2193 $submit->class = 'formsubmit';
2194 $submit->setValue('Login')
2195 ->setDecorators(array(
2197 array('helper' => 'formSubmit'))
2200 $this->addElements(array(
2206 $this->setDecorators(array(
2213 ]]></programlisting>
2216 This form can then be instantiated with simply:
2219 <programlisting language="php"><![CDATA[
2220 $form = new My_Form_Login();
2221 ]]></programlisting>
2224 and all functionality is already setup and ready; no config files
2225 needed. (Note that this example is greatly simplified, as it
2226 contains no validators or filters for the elements.)
2230 Another common reason for extension is to define a set of
2231 default decorators. You can do this by overriding the
2232 <methodname>loadDefaultDecorators()</methodname> method:
2235 <programlisting language="php"><![CDATA[
2236 class My_Form_Login extends Zend_Form
2238 public function loadDefaultDecorators()
2240 $this->setDecorators(array(
2247 ]]></programlisting>
2251 vim:se ts=4 sw=4 et: