A form consists of elements that generally correspond to HTML form input. Zend_form_element encapsulates a single form element and accomplishes the following: validation (the submitted data is valid.) The fetch checksum error code and message filtering (how the elements are escaped or normalized before the checksum/or output). ) parsing (How the element is displayed.) Metadata and attributes (what information further modifies the element.) )
The base class zend_form_element has a reasonable default setting for many classes, but it is better to inherit this class to complete the special intent element. In addition, the Zend Framework has many standard XHTML elements.
1. Plugin loader
Zend_form_element uses Zend_loader_pluginloader to enable developers to specify the location of alternative validators, filters, and adorners. Each has its own plug-in loader and uses a common accessor to read or modify them.
The following loader types are used with a variety of plug-in Loader methods: ' Validate ', ' filter ', and ' decorator '. The type name is case-sensitive.
the plug-in loader interacts with the following methods: Setpluginloader ($loader, $type):$loader is the plug-in loader object itself, and $type is one of these types. This method sets the plug-in loader of the given type to the latest specific carrier object. Getpluginloader ($type): reads the plug-in loader with the $type you carry. Addprefixpath ($prefix, $path, $type = null): adds a prefix/path union to the loader specified by the $type. If the $type is null, it will attempt to add the path to all loaders by appending the prefix to "_validate", "_filter", and "_decorator", using "validate/", "filter/", and "decorator/". Append path. If you have all the additional TABLE element classes under the generic hierarchy, this is a convenient way to set the underlying prefixes to them. addprefixpaths (array $spec): lets you add many paths at once to one or more plug-in loaders. It requires each array entry to be a ' path ', ' prefix ', and ' type '. The array of keys.
custom validators, filters, and adorners are simple ways to share functionality between forms and packaged custom functions.
Example 1. Custom Labels
A common use case for plug-ins is to provide replacements for standard classes. For example, if you want to implement a different ' label ' adorner-such as always append a colon-you can create your own ' label ' adorner with the class prefix and add it to your prefix path.
Let's start with a custom tag decorator, give it a class prefix "My_decorator", and the class file is "my/decorator/label.php".
<?php Classmy_decorator_label extends Zend_form_decorator_abstract {protected $_placement = ' prepend '; Public function render ($content) {if (null = = = ($element = $this->getelement ())) {return $cont
Ent
} if (!method_exists ($element, ' Getlabel ')) {return $content; } $label = $element->getlabel ().
':';
if (null = = = ($view = $element->getview ())) {Return$this->renderlabel ($content, $label);
} $label = $view->formlabel ($element->getname (), $label);
return $this->renderlabel ($content, $label);
The Public Function Renderlabel ($content, $label) {$placement = $this->getplacement ();
$separator = $this->getseparator ();
Switch ($placement) {case ' APPEND ': Return $content. $separator. $label; Case ' prepend ': Default:return $label.$separator. $content;
}
}
}
Now, when the element looks for the adorner, the plugin path is used:
$element->addprefixpath (' my_decorator ', ' my/decorator/', ' Decorator ');
In addition, we can do this at the table at a single level to ensure that all adorners use this path:
$form->addelementprefixpath (' my_decorator ', ' my/decorator/', ' Decorator ');
With this added path, when adding an adorner, the ' my/decorator/' path will be searched first to check for the presence of the adorner. As a result, if the ' Label ' adorner is requested, ' My_decorator_label ' will be used.
2. Filter
It is often useful and/or necessary to perform normalization on the input before validation-for example, you might want to strip all the HTML and run the checksum on the remainder to ensure that the commit is valid. Or you may want to eliminate the whitespace on both sides of the input data so that the Stringlength validator does not return a failure. These operations are performed using Zend_filter, and Zend_form_element supports the filter chain, allowing you to specify multiple successive filters to use. The checksum occurs during the check and reading of the element value through GetValue ():
<?php
$filtered = $element->getvalue ();
? >
There are two ways to add a filter: pass a specific filter instance to provide a filter name-a short name or full class names can be
See some examples:
<?php
//Specific filter Example:
$element->addfilter (Newzend_filter_alnum ());
Qualified full-class name:
$element->addfilter (' Zend_filter_alnum ');
Short Filter Name:
$element->addfilter (' Alnum ');
$element->addfilter (' Alnum ');
? >
The short name is usually the filter name to remove the prefix, the default is to remove the ' zend_filter_ ' prefix. In addition, the initial letter does not need to be capitalized.
|
using a custom filter class |
If you have your own set of filters, you can tell Zend_form_element by Addprefixpath (). For example, if you have a filter under the ' my_filter ' prefix, tell zend_form_element: <?php
$element->addprefixpath (' My_filter ', ' my/filter/', ' Filter ');
? >
(Recall that the third parameter is used to indicate which plug-in loader performs this action) |
Any time you need non-filtered data, use the Getunfilteredvalue () method:
<?php
$unfiltered = $element->getunfilteredvalue ();
? >
Filters with these methods: AddFilter ($nameOfFilter, array $options = null) addfilters (array $filters) setfilters (array $filters) (Override all filters) GetFilter ($name) (Read filter object by name) Getfilters () (Read all filters) removefilter ($name) (delete filter by name) clearfilters (delete all filters)
3. Calibrator
If you agree with the security Mantra "filter input, Escape output", you will be verifying ("filter input") your form input. In Zend_form, each element contains its own validator chain consisting of a zend_validate_* validator.
Two ways to add a validator to the validator chain: passing a specific validator instance provides a validator name-short name or full class names can be
See some examples:
<?php
//Concrete validatorinstance:
$element->addvalidator (Newzend_validate_alnum ());
Fully qualifiedclass Name:
$element->addvalidator (' Zend_validate_alnum ');
Short Validatorname:
$element->addvalidator (' Alnum ');
$element->addvalidator (' Alnum ');
? >
The short name is generally the validator name to remove the prefix, the default is to remove the ' zend_validate_ ' prefix. In addition, the initial letter does not need to be capitalized.
|
using a custom validator class |
If you have your own set of validators, you can tell Zend_form_element by Addprefixpath (). For example, if you have a validator under the ' my_validator ' prefix, tell zend_form_element: <?php $element->addprefixpath (' my_validator ', ' my/validator/', ' Validate '); ?> (Recall that the third parameter is used to indicate which plug-in loader performs this action) |
If a specific checksum fails, the second argument True (Boolean) is passed to prevent subsequent checksum work:
<?php
$element->addvalidator (' Alnum ', true);
? >
If you use a string name to add a validator, and the validator takes a parameter to the constructor, you can pass the third parameter Addvalidator () as an array:
<?php
$element->addvalidator (' Stringlength ', False, Array (6));
? >
Such passing parameters should be in the order in which they are defined in the constructor. The example above will instantiate the Zend_validate_stringlenth class with parameter $min and $max:
<?php
$validator = newzend_validate_stringlength (6);
? >
|
provides a custom checksum error message |
Some developers may want to provide custom error messages for the validator. The $options parameter of Zend_form_element::addvalidator () allows you to do this by providing the ' messages ' key and setting it as an array of key/value pairs (used to set the message template). You need to know the error codes for the various types of checksum errors for a particular validator. A slightly better choice is to use Zend_translate_adapter in the form. The error code is automatically passed to the adapter via the default error adorner, and you can specify your own error message string by setting the translation for the various error codes for your validator. |
You can also use Addvalidators () to set up many validators at once. The basic usage is to pass an array of arrays, each containing 1 to 3 values for the constructors that match Addvalidator (): (This may be used more often.) )
<?php
$element->addvalidators (Array ('
notempty ', true), array ('
alnum '), Array (
' Stringlength ', False, array (6,)))
;
>
if you want to make it clearer and more detailed, you can use the array keys ' validator ', ' breakchainonfailure ' and ' Options ':
<?php
$element->addvalidators (Array (
' validator ' = ' notempty ',
' Breakchainonfailure ' = True ',
Array (' validator ' = ' alnum '),
Array (
' validator ' = ' Stringlength ',
' options ' = = Array (6, +)))
;
>
This usage shows how to configure the validator in the configuration file:
Element.validators.notempty.validator= "Notempty"
element.validators.notempty.breakchainonfailure= true
Element.validators.alnum.validator= "Alnum"
element.validators.strlen.validator= "StringLength
" element.validators.strlen.options.min= 6
element.validators.strlen.options.max= 20
Note that each entry has a key, regardless of whether it is required, which is specified using a configuration file-but it also helps to understand clearly which parameter is used for what. Remember that any validator options must be specified sequentially.
To validate an element, pass the value to IsValid ():
<?php
if ($element->isvalid ($value)) {
//valid
} else {
//invalid
}
?>
Note: The above points are often used.
|
after the filtered value of the Colonel Test |
Zend_form_element::isvalid () filters (enters) values by providing a filter chain before validation. |
|
Validation Context |
Zend_form_element::isvalid () supports additional parameter $context. When validating a form zend_form::isvalid () passes the entire array of data processed by the $context, Zend_form_element::isvalid () then passes it to each validator. This means that you can write a validator that knows what data is being passed to other form elements, such as a standard registration form with a password and a password acknowledgment element, and a check that they match. The checker looks like this: <?php
class My_validate_passwordconfirmation extends Zend_validate_abstract
{
const Not_match = ' Notmatch ';
Protected $_messagetemplates = Array (
self::not_match = ' Password confirmation does not MATCH '
);
Public Function IsValid ($value, $context = null)
{
$value = (string) $value;
$this->_setvalue ($value);
if (Is_array ($context)) {
if (isset ($context [' password_confirm '))
&& ($value = = $context [' Password _confirm '])
{
return true;
}
} elseif (Is_string ($context) && ($value = = $context)) {
return true;
}
$this->_error (self::not_match);
return false;
}
}
? >
|
The validator is processed sequentially, unless the validator created with Breakchainonfailure is true and the checksum fails, otherwise each validator is processed. Confirm that your validator is specified in a reasonable order.
After the checksum fails, you can read the error code and message from the validator chain:
<?php
$errors = $element->geterrors ();
$messages = $element->getmessages ();
? >
(Note: The error message returns a union array with an error code/error message pair)
In addition to the validator, you can specify the required elements with setrequired (true). By default, this flag is false, and if no value is passed to IsValid (), the validator chain is skipped. You can also modify its behavior in a number of ways: By default, when an element is required, the flag ' AllowEmpty ' is also true. This means that if the value passed to IsValid () is null, the validator will be skipped. You can use the accessor setallowempty ($flag) to toggle this flag. When the flag is false and a value is passed, the validator will still run. By default, if the element is required but does not include the ' notempty ' validator, isValid () adds one to the top of the stack with the BREAKCHAINONFAILURE flag setting. This makes the required flags semantically meaningful: If no value is passed, we immediately invalidate the submitted data and notify the user, and prevent other validators from continuing to verify the invalid data we know.
If you don't want to, pass to Setautoinsertnotemptyvalidator ($flag) a false value to make it close. This will prevent isValid () from placing a ' notempty ' validator in the validator chain.
|
using Zend_form_elements as a general-purpose validator |
Zend_form_element implementation of Zend_validate_interface means that elements can be used as validators in other non-form-related check chains. |
Validation-related methods include: Setrequired ($flag) and isrequired () allow you to set and read the status of the ' required ' flag. When set to Boolean true, this flag requires that the element be in the data processed by Zend_form. Setallowempty ($flag) and getallowempty () let you modify the behavior of optional elements (for example, an element that requires a flag that is false). When the ' Allow empty ' flag is true, null values are passed to the validator chain. Setautoinsertnotemptyvalidator ($flag) When an element is required, let you specify whether the ' Notempty ' validator is pre-prepared to the validator chain. By default, this flag is true. Addvalidator ($nameOrValidator, $breakChainOnFailure = False, array $options = null) addvalidators (array $validators) Setvalidators (array $validators) (Overrides all validators) Getvalidator ($name) (reads the validator object by name) Getvalidators () (reads all validators) Removevalidator ( $name) (remove validators by name) clearvalidators () (Remove all validators)
4. Customizing error Messages
Sometimes, you want to customize one or more specific error messages to replace the error messages that come with the validator attached to the element. In addition, sometimes you want to mark the form as invalid, starting with 1.6.0, the following methods are used to implement this function. Adderrormessage ($message): Adds a bar to display error messages when the checksum fails. Can be called multiple times, and new messages are appended to the stack. Adderrormessages (array $messages): Adds multiple error messages to display a checksum error. Seterrormessages (Array $messages): Add multiple error messages to display the checksum error and overwrite the previous error message. Geterrormessages (): Reads a list of custom error messages that have been defined. Clearerrormessages (): Deletes the customized error message that has been defined. Markaserror (): Marked the form already has a failed checksum. HasErrors (): Determines whether the element has a failure check or is marked as invalid. Adderror ($message): Add a message to the stack of custom error messages and mark the form as invalid. Adderrors (Array $messages): Add several messages to the custom error message stack and mark the form as invalid. Seterrors (Array $messages): Overrides the custom error message stack and marks the form as invalid.
All errors set in this way can be translated.
5. Decorative Device
A particular pain for many web developers is the creation of XHTML forms themselves. For each element, the developer needs to generate Markup,label for the elements themselves, and if they are good to the user, they need to generate markup for the display checksum error message. The more page elements, the less trivial the task is.
Zend_form_element tried to use "decorator" to solve the problem. Adorners are classes that can access elements and methods used to parse content.
The default adorner used by Zend_form_element is: Viewhelper: Specifies that a view helper is used to parse the element. The ' helper ' element property can be used to specify which view helper to use. By default, zend_form_element specifies the ' formText ' view helper, but individual subclasses specify different assistants. Errors: Appends the error message to the element using zend_view_helper_formerrors, and does not append if there is no error. Htmltag: Encapsulates elements and errors in an HTML <dd> tag. Label: Use Zend_view_helper_formlabel to pre-prepare a label to the element and enclose it in a <dt> tag. If no label is provided, define the term (definition Terms) label (tag).
|
no need to load default adorner |
By default, the default adorner is loaded during object initialization. You can turn it off by passing the ' disableloaddefaultdecorators ' option to the constructor: <?php
$element = new Zend_form_element (' foo ', Array (' disableloaddefaultdecorators ' = true));
This option can be mixed with the attempt options, which are either array options or in the Zend_config object. |
Because of the reason that the adorner registers the order--register first--you need to make sure that the adorner is registered in the appropriate order, or that the replacement option is set in a healthy way. This is an example of registering a default adorner:
<?php
$this->adddecorators (Array (
' Viewhelper '), Array (
' Errors '),
array (' Htmltag ', Array (' tag ' = ' dd '),
array (' Label ', array (' tag ' = ' dt ')),))
;
>
The initial content is generated by the ' viewhelper ' adorner, which generates the form elements themselves. Next, the ' Errors ' adorner fetches the error message from the element. If there are any errors, it is passed to the ' formerrors ' view helper for parsing. The next adorner ' Htmltag ' encapsulates elements and errors in an HTML <dd> tag. Finally, the ' label ' adorner reads the tag of the element and passes it to the ' Formlabel ' view helper, encapsulated in an HTML <dt> tag. By default, the data is pre-prepared to the content, and the output is basically this:
<dt><labelfor= "foo" class= "optional" >Foo</label></dt>
<dd>
<input type= "Text" Name= "foo" id= "foo" value= "123"/>
<ul class= "errors" >
<li> "123" is not analphanumeric value</li>
</ul>
</dd>
|
use multiple adorners of the same type |
Internally, when the adorner is read, Zend_form_element uses the adorner's class as the query mechanism. As a result, you cannot register multiple adorners of the same type, and later adorners rewrite the previously existing adorners. To solve this problem, you can use aliases. Instead of passing the adorner or adorner name as the first argument to Adddecorator (), it passes an array with a single element, and the alias points to the adorner object or first name: <?php//Alias
To ' FooBar ': $element->adddecorator (Array (' FooBar ' = ' Htmltag '), array (' tag ' = ' div ')); And retrieve later: $decorator = $element->getdecorator (' FooBar '); in Adddecorators () and In the Setdecorators () method, you need to pass the ' decorator ' option in the array that represents the adorner: <?php//Add both ' Htmltag ' Decorators, aliasing one to ' FooBar ': $element->adddecorators (Array (' Htmltag ', array (' tag ' = ' div ')), Arra
Y (' decorator ' = = Array (' FooBar ' = ' htmltag '), ' options ' = = Array (' tag ' = ' dd '));
And retrieve later: $htmlTag = $element->getdecorator (' Htmltag '); $fooBar = $element->getdecorator (' FooBar '); |
The methods included with the adorner include: Adddecorator ($nameOrDecorator, array $options = null) adddecorators (array $decorators) setdecorators (array $decorators) (overriding all adorners) Getdecorator ($name) (read adorner object by name) Getdecorators () (Read all adorners) Removedecorator ($name) (remove adorner by name) Cleardecorators () (Remove all adorners)
6. Meta Data and Attributes
Zend_form_element handles a wide range of attribute and element metadata, including: name: The element name, using the SetName () and GetName () accessors. Label: element tag, using SetLabel () and Getlabel () accessors. Order: The index of the element that appears in the form, using the Setorder () and GetOrder () accessors. Value: The values of the current element, using the SetValue () and GetValue () accessors. Description: A description of an element, often used to provide ToolTips or JavaScript context hints, to describe the intent of elements, to use SetDescription () and GetDescription () accessors. Required: A flag indicating whether the element is required when performing form validation, using setrequired () and getrequired () accessors, the default is False. AllowEmpty: Indicates whether an optional element should verify the flag of a null value, when true, and the required flag is false, the null value is not passed to the validator chain, and is assumed to be true. Using the Setallowempty () and Getallowempty () accessors, the default is true. Autoinsertnotemptyvalidator: Indicates whether to insert a ' notempty ' validator when the element is required. By default, this flag is true, set the flag with Setautoinsertnotemptyvalidator ($flag) and use Autoinsertnotemptyvalidator () to determine its value.
The form element may require additional metadata. For example, for XHTML form elements, you might want to specify properties such as class or ID, with a set of accessors to complete it: Setattrib ($name, $value): Add Property setattribs (array $attribs): Like Addattribs (), But rewrite Getattrib ($name): Reads a single property value Getattribs (): reads all properties with key/value pairs
Most of the time, however, you can access them as object properties because Zend_form_element uses overloads to easily access them:
<?php
//equivalent To$element->setattrib (' class ', ' Text '):
$ele