1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.form.elements">
4 <title>Creating Form Elements Using Zend_Form_Element</title>
7 A form is made of elements that typically correspond to <acronym>HTML</acronym> form
8 input. <classname>Zend_Form_Element</classname> encapsulates single form elements, with the
9 following areas of responsibility:
15 validation (is submitted data valid?)
19 <listitem><para>capturing of validation error codes and messages</para></listitem>
25 filtering (how is the element escaped or normalized prior to
26 validation and/or for output?)
31 <para>rendering (how is the element displayed?)</para>
35 <para>metadata and attributes (what information further qualifies the element?)</para>
40 The base class, <classname>Zend_Form_Element</classname>, has reasonable defaults
41 for many cases, but it is best to extend the class for commonly used
42 special purpose elements. Additionally, Zend Framework ships with a
43 number of standard <acronym>XHTML</acronym> elements; you can read about them <link
44 linkend="zend.form.standardElements">in the Standard Elements
48 <sect2 id="zend.form.elements.loaders">
49 <title>Plugin Loaders</title>
52 <classname>Zend_Form_Element</classname> makes use of <link
53 linkend="zend.loader.pluginloader">Zend_Loader_PluginLoader</link>
54 to allow developers to specify locations of alternate validators,
55 filters, and decorators. Each has its own plugin loader associated
56 with it, and general accessors are used to retrieve and modify
61 The following loader types are used with the various plugin loader
62 methods: 'validate', 'filter', and 'decorator'. The type names are
67 The methods used to interact with plugin loaders are as follows:
73 <methodname>setPluginLoader($loader, $type)</methodname>:
74 <varname>$loader</varname> is the plugin loader object itself, while
75 <varname>$type</varname> is one of the types specified above. This
76 sets the plugin loader for the given type to the newly
77 specified loader object.
83 <methodname>getPluginLoader($type)</methodname>: retrieves the plugin
84 loader associated with <varname>$type</varname>.
90 <methodname>addPrefixPath($prefix, $path, $type = null)</methodname>: adds
91 a prefix/path association to the loader specified by
92 <varname>$type</varname>. If <varname>$type</varname> is
93 <constant>NULL</constant>, it will attempt to add the path to all loaders, by
94 appending the prefix with each of "_Validate", "_Filter", and "_Decorator"; and
95 appending the path with "Validate/", "Filter/", and
96 "Decorator/". If you have all your extra form element classes
97 under a common hierarchy, this is a convenience method for
98 setting the base prefix for them.
104 <methodname>addPrefixPaths(array $spec)</methodname>: allows you to add
105 many paths at once to one or more plugin loaders. It expects
106 each array item to be an array with the keys 'path', 'prefix',
113 Custom validators, filters, and decorators are an easy way to share
114 functionality between forms and to encapsulate custom functionality.
117 <example id="zend.form.elements.loaders.customLabel">
118 <title>Custom Label</title>
121 One common use case for plugins is to provide replacements for
122 standard classes. For instance, if you want to provide a
123 different implementation of the 'Label' decorator -- for
124 instance, to always append a colon -- you could create your own
125 'Label' decorator with your own class prefix, and then add it to
130 Let's start with a custom Label decorator. We'll give it the
131 class prefix "My_Decorator", and the class itself will be in the
132 file "My/Decorator/Label.php".
135 <programlisting language="php"><![CDATA[
136 class My_Decorator_Label extends Zend_Form_Decorator_Abstract
138 protected $_placement = 'PREPEND';
140 public function render($content)
142 if (null === ($element = $this->getElement())) {
145 if (!method_exists($element, 'getLabel')) {
149 $label = $element->getLabel() . ':';
151 if (null === ($view = $element->getView())) {
152 return $this->renderLabel($content, $label);
155 $label = $view->formLabel($element->getName(), $label);
157 return $this->renderLabel($content, $label);
160 public function renderLabel($content, $label)
162 $placement = $this->getPlacement();
163 $separator = $this->getSeparator();
165 switch ($placement) {
167 return $content . $separator . $label;
170 return $label . $separator . $content;
177 Now we can tell the element to use this plugin path when looking
181 <programlisting language="php"><![CDATA[
182 $element->addPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');
186 Alternately, we can do that at the form level to ensure all
187 decorators use this path:
190 <programlisting language="php"><![CDATA[
191 $form->addElementPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');
195 After it added as in the example above, the 'My/Decorator/' path will be searched
196 first to see if the decorator exists there when you add a decorator. As a result,
197 'My_Decorator_Label' will now be used when the 'Label' decorator is requested.
202 <sect2 id="zend.form.elements.filters">
203 <title>Filters</title>
206 It's often useful and/or necessary to perform some normalization on
207 input prior to validation. For example, you may want to strip out
208 all <acronym>HTML</acronym>, but run your validations on what remains to ensure the
209 submission is valid. Or you may want to trim empty space surrounding input so that a
210 StringLength validator will use the correct length of the input without counting leading
211 or trailing whitespace characters. These operations may be performed using
212 <classname>Zend_Filter</classname>. <classname>Zend_Form_Element</classname> has support
213 for filter chains, allowing you to specify multiple, sequential filters. Filtering
214 happens both during validation and when you retrieve the element value via
215 <methodname>getValue()</methodname>:
218 <programlisting language="php"><![CDATA[
219 $filtered = $element->getValue();
223 Filters may be added to the chain in two ways:
229 passing in a concrete filter instance
235 providing a short filter name
241 Let's see some examples:
244 <programlisting language="php"><![CDATA[
245 // Concrete filter instance:
246 $element->addFilter(new Zend_Filter_Alnum());
248 // Short filter name:
249 $element->addFilter('Alnum');
250 $element->addFilter('alnum');
254 Short names are typically the filter name minus the prefix. In the
255 default case, this will mean minus the 'Zend_Filter_' prefix.
256 The first letter can be upper-cased or lower-cased.
260 <title>Using Custom Filter Classes</title>
263 If you have your own set of filter classes, you can tell
264 <classname>Zend_Form_Element</classname> about these using
265 <methodname>addPrefixPath()</methodname>. For instance, if you have
266 filters under the 'My_Filter' prefix, you can tell
267 <classname>Zend_Form_Element</classname> about this as follows:
270 <programlisting language="php"><![CDATA[
271 $element->addPrefixPath('My_Filter', 'My/Filter/', 'filter');
275 (Recall that the third argument indicates which plugin loader
276 on which to perform the action.)
281 If at any time you need the unfiltered value, use the
282 <methodname>getUnfilteredValue()</methodname> method:
285 <programlisting language="php"><![CDATA[
286 $unfiltered = $element->getUnfilteredValue();
290 For more information on filters, see the <link
291 linkend="zend.filter.introduction">Zend_Filter
292 documentation</link>.
296 Methods associated with filters include:
302 <methodname>addFilter($nameOfFilter, array $options = null)</methodname>
308 <methodname>addFilters(array $filters)</methodname>
314 <methodname>setFilters(array $filters)</methodname> (overwrites all filters)
320 <methodname>getFilter($name)</methodname> (retrieve a filter object by name)
326 <methodname>getFilters()</methodname> (retrieve all filters)
332 <methodname>removeFilter($name)</methodname> (remove filter by name)
338 <methodname>clearFilters()</methodname> (remove all filters)
344 <sect2 id="zend.form.elements.validators">
345 <title>Validators</title>
348 If you subscribe to the security mantra of "filter input, escape
349 output," you'll should use validator to filter input submitted with your form.
350 In <classname>Zend_Form</classname>, each element includes its own validator
351 chain, consisting of <classname>Zend_Validate_*</classname> validators.
355 Validators may be added to the chain in two ways:
361 passing in a concrete validator instance
367 providing a short validator name
373 Let's see some examples:
376 <programlisting language="php"><![CDATA[
377 // Concrete validator instance:
378 $element->addValidator(new Zend_Validate_Alnum());
380 // Short validator name:
381 $element->addValidator('Alnum');
382 $element->addValidator('alnum');
386 Short names are typically the validator name minus the prefix. In
387 the default case, this will mean minus the 'Zend_Validate_' prefix.
388 As is the case with filters, the first letter can be upper-cased or lower-cased.
392 <title>Using Custom Validator Classes</title>
395 If you have your own set of validator classes, you can tell
396 <classname>Zend_Form_Element</classname> about these using
397 <methodname>addPrefixPath()</methodname>. For instance, if you have
398 validators under the 'My_Validator' prefix, you can tell
399 <classname>Zend_Form_Element</classname> about this as follows:
402 <programlisting language="php"><![CDATA[
403 $element->addPrefixPath('My_Validator', 'My/Validator/', 'validate');
407 (Recall that the third argument indicates which plugin loader
408 on which to perform the action.)
413 If failing a particular validation should prevent later validators
414 from firing, pass boolean <constant>TRUE</constant> as the second parameter:
417 <programlisting language="php"><![CDATA[
418 $element->addValidator('alnum', true);
422 If you are using a string name to add a validator, and the
423 validator class accepts arguments to the constructor, you may pass
424 these to the third parameter of <methodname>addValidator()</methodname> as an
428 <programlisting language="php"><![CDATA[
429 $element->addValidator('StringLength', false, array(6, 20));
433 Arguments passed in this way should be in the order in which they
434 are defined in the constructor. The above example will instantiate
435 the <classname>Zend_Validate_StringLenth</classname> class with its
436 <varname>$min</varname> and <varname>$max</varname> parameters:
439 <programlisting language="php"><![CDATA[
440 $validator = new Zend_Validate_StringLength(6, 20);
444 <title>Providing Custom Validator Error Messages</title>
447 Some developers may wish to provide custom error messages for a
448 validator. The <varname>$options</varname> argument of the
449 <methodname>Zend_Form_Element::addValidator()</methodname> method allows you to do
450 so by providing the key 'messages' and mapping it to an array of key/value pairs
451 for setting the message templates. You will need to know the
452 error codes of the various validation error types for the
453 particular validator.
457 A better option is to use a <classname>Zend_Translate_Adapter</classname>
458 with your form. Error codes are automatically passed to the
459 adapter by the default Errors decorator; you can then specify
460 your own error message strings by setting up translations for
461 the various error codes of your validators.
466 You can also set many validators at once, using
467 <methodname>addValidators()</methodname>. The basic usage is to pass an array
468 of arrays, with each array containing 1 to 3 values, matching the
469 constructor of <methodname>addValidator()</methodname>:
472 <programlisting language="php"><![CDATA[
473 $element->addValidators(array(
474 array('NotEmpty', true),
476 array('stringLength', false, array(6, 20)),
481 If you want to be more verbose or explicit, you can use the array
482 keys 'validator', 'breakChainOnFailure', and 'options':
485 <programlisting language="php"><![CDATA[
486 $element->addValidators(array(
488 'validator' => 'NotEmpty',
489 'breakChainOnFailure' => true),
490 array('validator' => 'alnum'),
492 'validator' => 'stringLength',
493 'options' => array(6, 20)),
498 This usage is good for illustrating how you could then configure
499 validators in a config file:
502 <programlisting language="ini"><![CDATA[
503 element.validators.notempty.validator = "NotEmpty"
504 element.validators.notempty.breakChainOnFailure = true
505 element.validators.alnum.validator = "Alnum"
506 element.validators.strlen.validator = "StringLength"
507 element.validators.strlen.options.min = 6
508 element.validators.strlen.options.max = 20
512 Notice that every item has a key, whether or not it needs one; this
513 is a limitation of using configuration files -- but it also helps
514 make explicit what the arguments are for. Just remember that any
515 validator options must be specified in order.
519 To validate an element, pass the value to
520 <methodname>isValid()</methodname>:
523 <programlisting language="php"><![CDATA[
524 if ($element->isValid($value)) {
532 <title>Validation Operates On Filtered Values</title>
535 <methodname>Zend_Form_Element::isValid()</methodname> filters values through
536 the provided filter chain prior to validation. See <link
537 linkend="zend.form.elements.filters">the Filters
538 section</link> for more information.
543 <title>Validation Context</title>
546 <methodname>Zend_Form_Element::isValid()</methodname> supports an
547 additional argument, <varname>$context</varname>.
548 <methodname>Zend_Form::isValid()</methodname> passes the entire array of
549 data being processed to <varname>$context</varname> when validating a
550 form, and <methodname>Zend_Form_Element::isValid()</methodname>, in turn,
551 passes it to each validator. This means you can write
552 validators that are aware of data passed to other form
553 elements. As an example, consider a standard registration form
554 that has fields for both password and a password confirmation;
555 one validation would be that the two fields match. Such a
556 validator might look like the following:
559 <programlisting language="php"><![CDATA[
560 class My_Validate_PasswordConfirmation extends Zend_Validate_Abstract
562 const NOT_MATCH = 'notMatch';
564 protected $_messageTemplates = array(
565 self::NOT_MATCH => 'Password confirmation does not match'
568 public function isValid($value, $context = null)
570 $value = (string) $value;
571 $this->_setValue($value);
573 if (is_array($context)) {
574 if (isset($context['password_confirm'])
575 && ($value == $context['password_confirm']))
579 } elseif (is_string($context) && ($value == $context)) {
583 $this->_error(self::NOT_MATCH);
591 Validators are processed in order. Each validator is processed,
592 unless a validator created with a <constant>TRUE</constant>
593 <varname>$breakChainOnFailure</varname> value fails its validation. Be
594 sure to specify your validators in a reasonable order.
598 After a failed validation, you can retrieve the error codes and
599 messages from the validator chain:
602 <programlisting language="php"><![CDATA[
603 $errors = $element->getErrors();
604 $messages = $element->getMessages();
608 (Note: error messages returned are an associative array of error
609 code / error message pairs.)
613 In addition to validators, you can specify that an element is
614 required, using <methodname>setRequired($flag)</methodname>. By default, this
615 flag is <constant>FALSE</constant>. In combination with
616 <methodname>setAllowEmpty($flag)</methodname> (<constant>TRUE</constant>
617 by default) and <methodname>setAutoInsertNotEmptyValidator($flag)</methodname>
618 (<constant>TRUE</constant> by default), the behavior of your validator chain
619 can be modified in a number of ways:
625 Using the defaults, validating an Element without passing a value, or
626 passing an empty string for it, skips all validators and validates to
627 <constant>TRUE</constant>.
633 <methodname>setAllowEmpty(false)</methodname> leaving the two other
634 mentioned flags untouched, will validate against the validator chain
635 you defined for this Element, regardless of the value passed
636 to <methodname>isValid()</methodname>.
642 <methodname>setRequired(true)</methodname> leaving the two other
643 mentioned flags untouched, will add a 'NotEmpty' validator
644 on top of the validator chain (if none was already set)), with the
645 <varname>$breakChainOnFailure</varname> flag set. This behavior lends
646 required flag semantic meaning: if no value is passed,
647 we immediately invalidate the submission and notify the
648 user, and prevent other validators from running on what we
649 already know is invalid data.
653 If you do not want this behavior, you can turn it off by
654 passing a <constant>FALSE</constant> value to
655 <methodname>setAutoInsertNotEmptyValidator($flag)</methodname>; this
656 will prevent <methodname>isValid()</methodname> from placing the
657 'NotEmpty' validator in the validator chain.
663 For more information on validators, see the <link
664 linkend="zend.validate.introduction">Zend_Validate
665 documentation</link>.
669 <title>Using Zend_Form_Elements as general-purpose validators</title>
672 <classname>Zend_Form_Element</classname> implements
673 <classname>Zend_Validate_Interface</classname>, meaning an element may
674 also be used as a validator in other, non-form related
680 <title>When is an element detected as empty?</title>
683 As mentioned the 'NotEmpty' validator is used to detect if an element is empty
684 or not. But <classname>Zend_Validate_NotEmpty</classname> does, per default, not
685 work like <acronym>PHP</acronym>'s method <methodname>empty()</methodname>.
689 This means when an element contains an integer <emphasis>0</emphasis> or an string
690 <emphasis>'0'</emphasis> then the element will be seen as not empty. If you want to
691 have a different behaviour you must create your own instance of
692 <classname>Zend_Validate_NotEmpty</classname>. There you can define the behaviour of
693 this validator. See <ulink
694 url="zend.validate.set.notempty">Zend_Validate_NotEmpty</ulink> for details.
699 Methods associated with validation include:
705 <methodname>setRequired($flag)</methodname> and
706 <methodname>isRequired()</methodname> allow you to set and retrieve the
707 status of the 'required' flag. When set to boolean <constant>TRUE</constant>,
708 this flag requires that the element be in the data processed by
709 <classname>Zend_Form</classname>.
715 <methodname>setAllowEmpty($flag)</methodname> and
716 <methodname>getAllowEmpty()</methodname> allow you to modify the
717 behaviour of optional elements (i.e., elements where the
718 required flag is <constant>FALSE</constant>). When the 'allow empty' flag is
719 <constant>TRUE</constant>, empty values will not be passed to the validator
726 <methodname>setAutoInsertNotEmptyValidator($flag)</methodname> allows
727 you to specify whether or not a 'NotEmpty' validator will be
728 prepended to the validator chain when the element is
729 required. By default, this flag is <constant>TRUE</constant>.
735 <methodname>addValidator($nameOrValidator, $breakChainOnFailure = false, array
736 $options = null)</methodname>
742 <methodname>addValidators(array $validators)</methodname>
748 <methodname>setValidators(array $validators)</methodname> (overwrites all
755 <methodname>getValidator($name)</methodname> (retrieve a validator object by
762 <methodname>getValidators()</methodname> (retrieve all validators)
768 <methodname>removeValidator($name)</methodname> (remove validator by name)
774 <methodname>clearValidators()</methodname> (remove all validators)
779 <sect3 id="zend.form.elements.validators.errors">
780 <title>Custom Error Messages</title>
783 At times, you may want to specify one or more specific error
784 messages to use instead of the error messages generated by the
785 validators attached to your element. Additionally, at times you
786 may want to mark the element invalid yourself. As of 1.6.0, this
787 functionality is possible via the following methods.
793 <methodname>addErrorMessage($message)</methodname>: add an error message
794 to display on form validation errors. You may call this more
795 than once, and new messages are appended to the stack.
801 <methodname>addErrorMessages(array $messages)</methodname>: add multiple
802 error messages to display on form validation errors.
808 <methodname>setErrorMessages(array $messages)</methodname>: add multiple
809 error messages to display on form validation errors,
810 overwriting all previously set error messages.
816 <methodname>getErrorMessages()</methodname>: retrieve the list of
817 custom error messages that have been defined.
823 <methodname>clearErrorMessages()</methodname>: remove all custom error
824 messages that have been defined.
830 <methodname>markAsError()</methodname>: mark the element as having
837 <methodname>hasErrors()</methodname>: determine whether the element has
838 either failed validation or been marked as invalid.
844 <methodname>addError($message)</methodname>: add a message to the custom
845 error messages stack and flag the element as invalid.
851 <methodname>addErrors(array $messages)</methodname>: add several
852 messages to the custom error messages stack and flag the
859 <methodname>setErrors(array $messages)</methodname>: overwrite the
860 custom error messages stack with the provided messages and
861 flag the element as invalid.
867 All errors set in this fashion may be translated. Additionally,
868 you may insert the placeholder "%value%" to represent the
869 element value; this current element value will be substituted
870 when the error messages are retrieved.
875 <sect2 id="zend.form.elements.decorators">
876 <title>Decorators</title>
879 One particular pain point for many web developers is the creation
880 of the <acronym>XHTML</acronym> forms themselves. For each element, the developer
881 needs to create markup for the element itself (typically a label)
882 and special markup for displaying
883 validation error messages. The more elements on the page, the less
884 trivial this task becomes.
888 <classname>Zend_Form_Element</classname> tries to solve this issue through
889 the use of "decorators". Decorators are simply classes that have
890 access to the element and a method for rendering content. For more
891 information on how decorators work, please see the section on <link
892 linkend="zend.form.decorators">Zend_Form_Decorator</link>.
896 The default decorators used by <classname>Zend_Form_Element</classname> are:
902 <emphasis>ViewHelper</emphasis>: specifies a view helper to use
903 to render the element. The 'helper' element attribute can be
904 used to specify which view helper to use. By default,
905 <classname>Zend_Form_Element</classname> specifies the 'formText' view
906 helper, but individual subclasses specify different helpers.
912 <emphasis>Errors</emphasis>: appends error messages to the
913 element using <classname>Zend_View_Helper_FormErrors</classname>. If none are
914 present, nothing is appended.
920 <emphasis>Description</emphasis>: appends the element
921 description. If none is present, nothing is appended. By
922 default, the description is rendered in a <p> tag with a
923 class of 'description'.
929 <emphasis>HtmlTag</emphasis>: wraps the element and errors in
930 an <acronym>HTML</acronym> <dd> tag.
936 <emphasis>Label</emphasis>: prepends a label to the element
937 using <classname>Zend_View_Helper_FormLabel</classname>, and wraps it in a
938 <dt> tag. If no label is provided, just the definition term tag is
945 <title>Default Decorators Do Not Need to Be Loaded</title>
948 By default, the default decorators are loaded during object
949 initialization. You can disable this by passing the
950 'disableLoadDefaultDecorators' option to the constructor:
953 <programlisting language="php"><![CDATA[
954 $element = new Zend_Form_Element('foo',
955 array('disableLoadDefaultDecorators' =>
961 This option may be mixed with any other options you pass,
962 both as array options or in a <classname>Zend_Config</classname> object.
967 Since the order in which decorators are registered matters- the first
968 decorator registered is executed first- you will need to make
969 sure you register your decorators in an appropriate order, or
970 ensure that you set the placement options in a sane fashion. To
971 give an example, here is the code that registers the default
975 <programlisting language="php"><![CDATA[
976 $this->addDecorators(array(
979 array('Description', array('tag' => 'p', 'class' => 'description')),
980 array('HtmlTag', array('tag' => 'dd')),
981 array('Label', array('tag' => 'dt')),
986 The initial content is created by the 'ViewHelper' decorator, which
987 creates the form element itself. Next, the 'Errors' decorator
988 fetches error messages from the element, and, if any are present,
989 passes them to the 'FormErrors' view helper to render. If a
990 description is present, the 'Description' decorator will append a
991 paragraph of class 'description' containing the descriptive text to
992 the aggregated content. The next decorator, 'HtmlTag', wraps the
993 element, errors, and description in an <acronym>HTML</acronym> <dd> tag.
994 Finally, the last decorator, 'label', retrieves the element's label
995 and passes it to the 'FormLabel' view helper, wrapping it in an <acronym>HTML</acronym>
996 <dt> tag; the value is prepended to the content by default.
997 The resulting output looks basically like this:
1000 <programlisting language="html"><![CDATA[
1001 <dt><label for="foo" class="optional">Foo</label></dt>
1003 <input type="text" name="foo" id="foo" value="123" />
1005 <li>"123" is not an alphanumeric value</li>
1007 <p class="description">
1008 This is some descriptive text regarding the element.
1011 ]]></programlisting>
1014 For more information on decorators, read the <link
1015 linkend="zend.form.decorators">Zend_Form_Decorator section</link>.
1019 <title>Using Multiple Decorators of the Same Type</title>
1022 Internally, <classname>Zend_Form_Element</classname> uses a decorator's
1023 class as the lookup mechanism when retrieving decorators. As a
1024 result, you cannot register multiple decorators of the same
1025 type; subsequent decorators will simply overwrite those that
1030 To get around this, you can use <emphasis>aliases</emphasis>.
1031 Instead of passing a decorator or decorator name as the first
1032 argument to <methodname>addDecorator()</methodname>, pass an array with a
1033 single element, with the alias pointing to the decorator object
1037 <programlisting language="php"><![CDATA[
1038 // Alias to 'FooBar':
1039 $element->addDecorator(array('FooBar' => 'HtmlTag'),
1040 array('tag' => 'div'));
1042 // And retrieve later:
1043 $decorator = $element->getDecorator('FooBar');
1044 ]]></programlisting>
1047 In the <methodname>addDecorators()</methodname> and
1048 <methodname>setDecorators()</methodname> methods, you will need to pass
1049 the 'decorator' option in the array representing the decorator:
1052 <programlisting language="php"><![CDATA[
1053 // Add two 'HtmlTag' decorators, aliasing one to 'FooBar':
1054 $element->addDecorators(
1055 array('HtmlTag', array('tag' => 'div')),
1057 'decorator' => array('FooBar' => 'HtmlTag'),
1058 'options' => array('tag' => 'dd')
1062 // And retrieve later:
1063 $htmlTag = $element->getDecorator('HtmlTag');
1064 $fooBar = $element->getDecorator('FooBar');
1065 ]]></programlisting>
1069 Methods associated with decorators include:
1075 <methodname>addDecorator($nameOrDecorator, array $options = null)</methodname>
1081 <methodname>addDecorators(array $decorators)</methodname>
1087 <methodname>setDecorators(array $decorators)</methodname> (overwrites all
1094 <methodname>getDecorator($name)</methodname> (retrieve a decorator object by
1101 <methodname>getDecorators()</methodname> (retrieve all decorators)
1107 <methodname>removeDecorator($name)</methodname> (remove decorator by name)
1113 <methodname>clearDecorators()</methodname> (remove all decorators)
1119 <classname>Zend_Form_Element</classname> also uses overloading to allow rendering
1120 specific decorators. <methodname>__call()</methodname> will intercept methods
1121 that lead with the text 'render' and use the remainder of the method
1122 name to lookup a decorator; if found, it will then render that
1123 <emphasis>single</emphasis> decorator. Any arguments passed to the
1124 method call will be used as content to pass to the decorator's
1125 <methodname>render()</methodname> method. As an example:
1128 <programlisting language="php"><![CDATA[
1129 // Render only the ViewHelper decorator:
1130 echo $element->renderViewHelper();
1132 // Render only the HtmlTag decorator, passing in content:
1133 echo $element->renderHtmlTag("This is the html tag content");
1134 ]]></programlisting>
1137 If the decorator does not exist, an exception is raised.
1141 <sect2 id="zend.form.elements.metadata">
1142 <title>Metadata and Attributes</title>
1145 <classname>Zend_Form_Element</classname> handles a variety of attributes and
1146 element metadata. Basic attributes include:
1152 <emphasis>name</emphasis>: the element name. Uses the
1153 <methodname>setName()</methodname> and <methodname>getName()</methodname>
1160 <emphasis>label</emphasis>: the element label. Uses the
1161 <methodname>setLabel()</methodname> and <methodname>getLabel()</methodname>
1168 <emphasis>order</emphasis>: the index at which an element
1169 should appear in the form. Uses the <methodname>setOrder()</methodname> and
1170 <methodname>getOrder()</methodname> accessors.
1176 <emphasis>value</emphasis>: the current element value. Uses the
1177 <methodname>setValue()</methodname> and <methodname>getValue()</methodname>
1184 <emphasis>description</emphasis>: a description of the element;
1185 often used to provide tooltip or javascript contextual hinting
1186 describing the purpose of the element. Uses the
1187 <methodname>setDescription()</methodname> and
1188 <methodname>getDescription()</methodname> accessors.
1194 <emphasis>required</emphasis>: flag indicating whether or not
1195 the element is required when performing form validation. Uses
1196 the <methodname>setRequired()</methodname> and
1197 <methodname>getRequired()</methodname> accessors. This flag is
1198 <constant>FALSE</constant> by default.
1204 <emphasis>allowEmpty</emphasis>: flag indicating whether or not
1205 a non-required (optional) element should attempt to validate
1206 empty values. If it is set to <constant>TRUE</constant> and the required flag is
1207 <constant>FALSE</constant>, empty values are not passed to the validator chain
1208 and are presumed <constant>TRUE</constant>. Uses the
1209 <methodname>setAllowEmpty()</methodname> and
1210 <methodname>getAllowEmpty()</methodname> accessors. This flag is
1211 <constant>TRUE</constant> by default.
1217 <emphasis>autoInsertNotEmptyValidator</emphasis>: flag
1218 indicating whether or not to insert a 'NotEmpty' validator when
1219 the element is required. By default, this flag is <constant>TRUE</constant>. Set
1220 the flag with <methodname>setAutoInsertNotEmptyValidator($flag)</methodname> and
1221 determine the value with
1222 <methodname>autoInsertNotEmptyValidator()</methodname>.
1228 Form elements may require additional metadata. For <acronym>XHTML</acronym> form
1229 elements, for instance, you may want to specify attributes such as
1230 the class or id. To facilitate this are a set of accessors:
1236 <emphasis>setAttrib($name, $value)</emphasis>: add an attribute
1242 <emphasis>setAttribs(array $attribs)</emphasis>: like
1243 addAttribs(), but overwrites
1249 <emphasis>getAttrib($name)</emphasis>: retrieve a single
1256 <emphasis>getAttribs()</emphasis>: retrieve all attributes as
1263 Most of the time, however, you can simply access them as object
1264 properties, as <classname>Zend_Form_Element</classname> utilizes overloading
1265 to facilitate access to them:
1268 <programlisting language="php"><![CDATA[
1269 // Equivalent to $element->setAttrib('class', 'text'):
1270 $element->class = 'text;
1271 ]]></programlisting>
1274 By default, all attributes are passed to the view helper used by
1275 the element during rendering, and rendered as <acronym>HTML</acronym> attributes of
1280 <sect2 id="zend.form.elements.standard">
1281 <title>Standard Elements</title>
1284 <classname>Zend_Form</classname> ships with a number of standard elements; please read
1285 the <link linkend="zend.form.standardElements">Standard Elements</link>
1286 chapter for full details.
1290 <sect2 id="zend.form.elements.methods">
1291 <title>Zend_Form_Element Methods</title>
1294 <classname>Zend_Form_Element</classname> has many, many methods. What follows
1295 is a quick summary of their signatures, grouped by type:
1300 <para>Configuration:</para>
1304 <para><methodname>setOptions(array $options)</methodname></para>
1308 <para><methodname>setConfig(Zend_Config $config)</methodname></para>
1319 <methodname>setTranslator(Zend_Translate_Adapter $translator
1320 = null)</methodname>
1324 <listitem><para><methodname>getTranslator()</methodname></para></listitem>
1327 <para><methodname>setDisableTranslator($flag)</methodname></para>
1331 <para><methodname>translatorIsDisabled()</methodname></para>
1337 <para>Properties:</para>
1340 <listitem><para><methodname>setName($name)</methodname></para></listitem>
1341 <listitem><para><methodname>getName()</methodname></para></listitem>
1342 <listitem><para><methodname>setValue($value)</methodname></para></listitem>
1343 <listitem><para><methodname>getValue()</methodname></para></listitem>
1344 <listitem><para><methodname>getUnfilteredValue()</methodname></para></listitem>
1345 <listitem><para><methodname>setLabel($label)</methodname></para></listitem>
1346 <listitem><para><methodname>getLabel()</methodname></para></listitem>
1349 <para><methodname>setDescription($description)</methodname></para>
1352 <listitem><para><methodname>getDescription()</methodname></para></listitem>
1353 <listitem><para><methodname>setOrder($order)</methodname></para></listitem>
1354 <listitem><para><methodname>getOrder()</methodname></para></listitem>
1355 <listitem><para><methodname>setRequired($flag)</methodname></para></listitem>
1356 <listitem><para><methodname>getRequired()</methodname></para></listitem>
1357 <listitem><para><methodname>setAllowEmpty($flag)</methodname></para></listitem>
1358 <listitem><para><methodname>getAllowEmpty()</methodname></para></listitem>
1361 <para><methodname>setAutoInsertNotEmptyValidator($flag)</methodname></para>
1365 <para><methodname>autoInsertNotEmptyValidator()</methodname></para>
1368 <listitem><para><methodname>setIgnore($flag)</methodname></para></listitem>
1369 <listitem><para><methodname>getIgnore()</methodname></para></listitem>
1370 <listitem><para><methodname>getType()</methodname></para></listitem>
1373 <para><methodname>setAttrib($name, $value)</methodname></para>
1377 <para><methodname>setAttribs(array $attribs)</methodname></para>
1380 <listitem><para><methodname>getAttrib($name)</methodname></para></listitem>
1381 <listitem><para><methodname>getAttribs()</methodname></para></listitem>
1386 <para>Plugin loaders and paths:</para>
1391 <methodname>setPluginLoader(Zend_Loader_PluginLoader_Interface $loader,
1397 <para><methodname>getPluginLoader($type)</methodname></para>
1402 <methodname>addPrefixPath($prefix, $path, $type = null)</methodname>
1407 <para><methodname>addPrefixPaths(array $spec)</methodname></para>
1413 <para>Validation:</para>
1418 <methodname>addValidator($validator, $breakChainOnFailure = false,
1419 $options = array())</methodname>
1424 <para><methodname>addValidators(array $validators)</methodname></para>
1428 <para><methodname>setValidators(array $validators)</methodname></para>
1431 <listitem><para><methodname>getValidator($name)</methodname></para></listitem>
1432 <listitem><para><methodname>getValidators()</methodname></para></listitem>
1435 <para><methodname>removeValidator($name)</methodname></para>
1438 <listitem><para><methodname>clearValidators()</methodname></para></listitem>
1441 <para><methodname>isValid($value, $context = null)</methodname></para>
1444 <listitem><para><methodname>getErrors()</methodname></para></listitem>
1445 <listitem><para><methodname>getMessages()</methodname></para></listitem>
1450 <para>Filters:</para>
1454 <para><methodname>addFilter($filter, $options = array())</methodname></para>
1458 <para><methodname>addFilters(array $filters)</methodname></para>
1462 <para><methodname>setFilters(array $filters)</methodname></para>
1465 <listitem><para><methodname>getFilter($name)</methodname></para></listitem>
1466 <listitem><para><methodname>getFilters()</methodname></para></listitem>
1467 <listitem><para><methodname>removeFilter($name)</methodname></para></listitem>
1468 <listitem><para><methodname>clearFilters()</methodname></para></listitem>
1473 <para>Rendering:</para>
1478 <methodname>setView(Zend_View_Interface $view = null)</methodname>
1482 <listitem><para><methodname>getView()</methodname></para></listitem>
1486 <methodname>addDecorator($decorator, $options = null)</methodname>
1491 <para><methodname>addDecorators(array $decorators)</methodname></para>
1495 <para><methodname>setDecorators(array $decorators)</methodname></para>
1498 <listitem><para><methodname>getDecorator($name)</methodname></para></listitem>
1499 <listitem><para><methodname>getDecorators()</methodname></para></listitem>
1502 <para><methodname>removeDecorator($name)</methodname></para>
1505 <listitem><para><methodname>clearDecorators()</methodname></para></listitem>
1509 <methodname>render(Zend_View_Interface $view = null)</methodname>
1517 <sect2 id="zend.form.elements.config">
1518 <title>Configuration</title>
1521 <classname>Zend_Form_Element</classname>'s constructor accepts either an
1522 array of options or a <classname>Zend_Config</classname> object containing
1523 options, and it can also be configured using either
1524 <methodname>setOptions()</methodname> or <methodname>setConfig()</methodname>. Generally
1525 speaking, keys are named as follows:
1531 If 'set' + key refers to a <classname>Zend_Form_Element</classname>
1532 method, then the value provided will be passed to that method.
1538 Otherwise, the value will be used to set an attribute.
1544 Exceptions to the rule include the following:
1550 <property>prefixPath</property> will be passed to
1551 <methodname>addPrefixPaths()</methodname>
1557 The following setters cannot be set in this way:
1563 <property>setAttrib</property> (though
1564 <property>setAttribs</property> <emphasis>will</emphasis> work)
1568 <listitem><para><property>setConfig</property></para></listitem>
1569 <listitem><para><property>setOptions</property></para></listitem>
1570 <listitem><para><property>setPluginLoader</property></para></listitem>
1571 <listitem><para><property>setTranslator</property></para></listitem>
1572 <listitem><para><property>setView</property></para></listitem>
1578 As an example, here is a config file that passes configuration for
1579 every type of configurable data:
1582 <programlisting language="ini"><![CDATA[
1590 autoInsertNotEmptyValidator = true
1591 description = "Foo elements are for examples"
1594 attribs.class = "element"
1595 ; sets 'onclick' attribute
1596 onclick = "autoComplete(this, '/form/autocomplete/element')"
1597 prefixPaths.decorator.prefix = "My_Decorator"
1598 prefixPaths.decorator.path = "My/Decorator/"
1599 disableTranslator = 0
1600 validators.required.validator = "NotEmpty"
1601 validators.required.breakChainOnFailure = true
1602 validators.alpha.validator = "alpha"
1603 validators.regex.validator = "regex"
1604 validators.regex.options.pattern = "/^[A-F].*/$"
1605 filters.ucase.filter = "StringToUpper"
1606 decorators.element.decorator = "ViewHelper"
1607 decorators.element.options.helper = "FormText"
1608 decorators.label.decorator = "Label"
1609 ]]></programlisting>
1612 <sect2 id="zend.form.elements.custom">
1613 <title>Custom Elements</title>
1616 You can create your own custom elements by simply extending the
1617 <classname>Zend_Form_Element</classname> class. Common reasons to do so
1624 Elements that share common validators and/or filters
1630 Elements that have custom decorator functionality
1636 There are two methods typically used to extend an element:
1637 <methodname>init()</methodname>, which can be used to add custom initialization
1638 logic to your element, and <methodname>loadDefaultDecorators()</methodname>,
1639 which can be used to set a list of default decorators used by your
1644 As an example, let's say that all text elements in a form you are
1645 creating need to be filtered with <classname>StringTrim</classname>,
1646 validated with a common regular expression, and that you want to
1647 use a custom decorator you've created for displaying them,
1648 'My_Decorator_TextItem'. In addition, you have a number of standard
1649 attributes, including 'size', 'maxLength', and 'class' you wish to
1650 specify. You could define an element to accomplish this as follows:
1653 <programlisting language="php"><![CDATA[
1654 class My_Element_Text extends Zend_Form_Element
1656 public function init()
1658 $this->addPrefixPath('My_Decorator', 'My/Decorator/', 'decorator')
1659 ->addFilters('StringTrim')
1660 ->addValidator('Regex', false, array('/^[a-z0-9]{6,}$/i'))
1661 ->addDecorator('TextItem')
1662 ->setAttrib('size', 30)
1663 ->setAttrib('maxLength', 45)
1664 ->setAttrib('class', 'text');
1667 ]]></programlisting>
1670 You could then inform your form object about the prefix path for
1671 such elements, and start creating elements:
1674 <programlisting language="php"><![CDATA[
1675 $form->addPrefixPath('My_Element', 'My/Element/', 'element')
1676 ->addElement('text', 'foo');
1677 ]]></programlisting>
1680 The 'foo' element will now be of type <classname>My_Element_Text</classname>,
1681 and exhibit the behaviour you've outlined.
1685 Another method you may want to override when extending
1686 <classname>Zend_Form_Element</classname> is the
1687 <methodname>loadDefaultDecorators()</methodname> method. This method
1688 conditionally loads a set of default decorators for your element;
1689 you may wish to substitute your own decorators in your extending
1693 <programlisting language="php"><![CDATA[
1694 class My_Element_Text extends Zend_Form_Element
1696 public function loadDefaultDecorators()
1698 $this->addDecorator('ViewHelper')
1699 ->addDecorator('DisplayError')
1700 ->addDecorator('Label')
1701 ->addDecorator('HtmlTag',
1702 array('tag' => 'div', 'class' => 'element'));
1705 ]]></programlisting>
1708 There are many ways to customize elements. Read the <acronym>API</acronym>
1709 documentation of <classname>Zend_Form_Element</classname> to learn about all of the
1715 vim:se ts=4 sw=4 tw=80 et: