Zend_form the basics of creating, validating, and parsing forms-(manuals)

Source: Internet
Author: User
Tags constructor error code http post lowercase min strlen zend framework


1. Create a Form object


Creating a Form object is simple: just implement Zend_form:

<?php
$form = newzend_form;
? >

For advanced use cases, you need to create subclasses of Zend_form, but for simple forms, programs can be created with Zend_form objects.

If you want to specify the actions and methods of the form (always a good idea), use Setaction () and Setmethod () to complete:

<?php
$form->setaction ('/resource/process ')
     ->setmethod (' post ');
? >

The above code sets the form action as part of the URL "/resource/process" and the form method is HTTP POST, which will be displayed during the final period of parsing.

You can set additional HTML properties for the <form> tag by using the Setattrib () or Setattribs () method, for example: If you want to set the ID, set the ID property:

<?php
$form->setattrib (' id ', ' login ');
>

2. Add Table element


Without elements, the form is nothing. Zend_form with some default elements that parse XHTML through the Zend_view Helper: Button checkbox (or many checkboxes at once with Multicheckbox) hidden image Password Radio Reset Select (both regular and multi-select types) Submit text textarea

There are two ways to add form elements: Instantiate specific elements and pass them, or pass element types and make Zend_form instantiate an object of the correct type.

Some examples:

<?php
//instantiating anelement and passing to the form object:
$form->addelement (newzend_form_element_ Text (' username '));
 
Passing a formelement type to the form object:
$form->addelement (' text ', ' username ');
? >

By default, these do not have validators and filters, and you need to configure elements with the most basic validators and possible filters. There are three ways of doing this:

(a) before passing the element to the form,

(b) The configuration options passed when creating elements with Zend_form,

(c) Pull the elements out from the form and configure them later.

Let's start by looking at creating a validator for a specific instance of the element. You can pass the Zend_validate_* object, or the name of the validator:

<?php
$username = Newzend_form_element_text (' username ');
 
Passing Azend_validate_* object:
$username->addvalidator (Newzend_validate_alnum ());
 
Passing Avalidator name:
$username->addvalidator (' Alnum ');
? >

When using the second method, if the validator can accept constructor arguments, you can put them in the array as the third parameter:

<?php
//Pass a pattern
$username->addvalidator (' regex ', False, Array ('/^[a-z]/i '));
? >

(the second parameter is used to indicate whether this check fails when the subsequent checksum is stopped, and the default is False.) )

You may also want to specify a required element that can be done by using an accessor or passing an option when creating the element, in the previous example:

<?php
//Make this element necessary:
$username->setrequired (true);
? >

When an element is required, a ' notempty ' validator is added to the top of the validator chain, ensuring that the element has a value.

Filters are registered like validators, for demonstration purposes, let's add a filter that turns the final value to lowercase:

<?php
$username->addfilter (' stringtolower ');
? >

In this way, the final element setting looks like this:

<?php
$username->addvalidator (' alnum ')
         ->addvalidator (' Regex ', False,array ('/^[a-z]/'))
         - >setrequired (True)
         ->addfilter (' stringtolower ');
 
Or, morecompactly:
$username->addvalidators (Array (' Alnum ',
        array (' regex ', false, '/^[a-z]/i '))
    )
    ->setrequired (True)
    ->addfilters (Array (' stringtolower '));
? >

Even so, it's tedious to do this work for every element in the form. Let's try the above method (b), when using the Factory mode Zend_form::addelement () to create a new element, we can optionally pass configuration options, including validators and filters. In this way, you can simply accomplish the above tasks:

<?php
$form->addelement (' text ', ' username ', array (
    ' validators ' = = Array (
        ' Alnum '),
        Array (' Regex ', false, '/^[a-z]/i ')
    ),
    ' required ' = = True,
    ' filters ' = = Array (' Stringtolower '),
));
? >

Note:

If you find that the same options are used to set elements in many places, consider creating your own zend_form_element subclass and using it, which in the long run can reduce the number of typing tasks.


3. Parse (Render) Form


Parsing the form is simple, and most elements are parsed using the Zend_view helper, which requires the view object to parse. In addition to this, there are two methods: Use the Render () method of the form or simply echo it.

<?php
//explicitly callingrender (), and passing an optional view object:
Echo$form->render ($view);
 
Assuming a viewobject has been previously set via Setview ():
echo $form;
? >

By default, Zend_form and Zend_form_element will attempt to use the view object that was initialized in Viewrenderer, and you do not need to manually set the view in Zend Framework MVC. Parsing a form in a view script is so simple:

<?= $this->form?>

Internally, Zend_form uses "decorators" (adorners) to perform parsing, which can replace content, append content, or pre-prepare content, and have full introspection of the elements passed to them. As a result, you can combine multiple adorners to achieve a custom effect. By default, Zend_form_element actually combines four adorners to complete the output, see the settings in the following example:

<?php
$element->adddecorators (Array ('
    viewhelper ',
    ' Errors ',
    array (' Htmltag ', array (' tag ') = ' dd '),
    array (' Label ', array (' tag ' = ' dt ')))
;
>

(<HELPERNAME> is the name of the View assistant and differs depending on the element)

The above example creates the following output:

<dt><labelfor= "username" class= "required" >Username</dt>
<dd>
    <input type= " Text "name=" username "value=" 123-abc "/>
    <ul class=" errors ">
        <li> ' 123-abc ' have not Onlyalphabetic and digit characters</li>
        <li> ' 123-abc ' does not matchagainst pattern '/^[a-z]/i ' </ li>
    </ul>
</dd>

(Although the same format is not used.) )

If you want to output something different, you can modify the adorner used by the element, see the adorner section for more content.

The form loops through all the elements and places them in HTML <form>. When you set up a form, the actions and methods that you provide are provided to the <form> tag, as well as any properties that are set by Setattribs () and its family.

Elements are either looped in the order in which they are registered or, if the elements contain sequential attributes, loop in that order. You can set the order of elements using the following methods:

<?php
$element->setorder (ten);
? >

Or, when creating an element, pass it as an option:

<?php
$form->addelement (' text ', ' username ', array (' order ' =]);
? >


4. Check if the form is valid


After the form is submitted, you need to check to see if it passes the checksum. Each element is checked against the provided data, and if the key that matches the element name does not appear and the entry is marked as required, it is validated with a null value.

Where the data comes from. Use $_post or $_get or other data sources on hand (such as Web service requests):

<?php
if ($form->isvalid ($_post)) {
    //success!
} else {
    //failure!
}
? >

With AJAX requests, it is sometimes possible to successfully validate a single element or a set of elements. Isvalidpartial () Officer partial form, unlike IsValid (), if a particular key does not appear, the element of that particular part is not verified:

<?php
if ($form->isvalidpartial ($_post)) {
    //elements present all passed validations
} else {
    // One or more elements tested failedvalidations
}
?>

An optional method, Processajax (), can also be used to validate a local form, unlike isvalidpartial (), if it fails, it returns a JSON-formatted string containing the error message.

Assuming that the checksum is passed, the filtered value can now be obtained:

<?php
$values = $form->getvalues ();
? >

If at any time you need a value that is not filtered, use:

<?php
$unfiltered = $form->getunfilteredvalues ();
? >


5. Get Error status


If the form validation fails, in most cases the form can be parsed again, and if the default adorner is used, the error message is displayed:

<?php
if (! $form->isvalid ($_post)) {
    echo $form;
 
    or assign to the View object and Rendera view
    ... $this->view->form = $form;
    return $this->render (' form ');
}
? >

If you want to insert an error message, there are two methods: GetErrors () returns a union array of element name/code pairs (the code here refers to an array of error codes). Getmessages () Returns a union array of element name/message pairs (here the message refers to the union array of error code/error message pairs). If the given element does not have any errors, the array does not contain it.


6. Put them together.


To create a simple login form, we need these elements: username password submit

Let's assume that a valid user name should be just an alphanumeric character, starting with a letter, a minimum of 6 characters, a maximum of 20 characters, and finally formatted in lowercase, with a minimum of 6 characters, and when this is done, we commit and remain unchecked.

We use the ability of the Zend_form configuration option to create a form:

<?php

$form = Newzend_form ();
$form->setaction ('/user/login ')
     ->setmethod (' post ');
 
Create andconfigure username element:
$username = $form->createelement (' text ', ' username ');
$username->addvalidator (' alnum ')
         ->addvalidator (' Regex ', False,array ('/^[a-z]+/'))
         Addvalidator (' Stringlength ', False, array (6,))
         ->setrequired (True)
         ->addfilter (' stringtolower ');
 
Create andconfigure Password element:
$password = $form->createelement (' Password ', ' password ');
$password->addvalidator (' Stringlength ', False, Array (6))
         ->setrequired (true);
 
ADD elements Toform:
$form->addelement ($username)
     ->addelement ($password)
     //Use AddElement () as a factory to create ' login ' button:
     ->addelement (' Submit ', ' login ', Array (' label ' = ' login '));
>

Next, we will create the controller to handle these:

<?php
class Usercontrollerextends zend_controller_action
{public
    function getform ()
    {
        // Create form as above
        return $form;
    }
 
    Public Function indexaction ()
    {
        //render user/form.phtml
        $this->view->form = $this->getform () ;
        $this->render (' form ');
    }
 
    Public Function loginaction ()
    {
        if (! $this->getrequest ()->ispost ()) {
            return $this->_ Forward (' index ');
        }
        $form = $this->getform ();
        if (! $form->isvalid ($_post)) {
            //Failed validation; Redisplayform
            $this->view->form = $form;
            return $this->render (' form ');
        }
 
        $values = $form->getvalues ();
        Now try and authenticate ...
    }
? >

And a view script to show the form:

 

Note In the controller code, there is a lot more to do: for example, after submission, you need to use Zend_auth to authenticate.


7. Using the Zend_config object


All Zend_form classes can be configured with Zend_config and can be passed Zend_config objects to the constructor or through Setconfig (). Take a look at how to create the above form with an INI file, first, follow the recommendations, put the configuration in the section that reflects the release location, and focus on the ' development ' section, and then set a section for the given controller (' user ') to set a key for the form (' login '):

[Development]; General Formmetainformation user.login.action = "/user/login" User.login.method = "POST";
Username element user.login.elements.username.type= "text"
User.login.elements.username.options.validators.alnum.validator= "Alnum"
User.login.elements.username.options.validators.regex.validator= "Regex"
User.login.elements.username.options.validators.regex.options.pattern= "/^[a-z]/i"
User.login.elements.username.options.validators.strlen.validator= "Stringlength"
User.login.elements.username.options.validators.strlen.options.min= "6"
user.login.elements.username.options.validators.strlen.options.max= "20" user.login.elements.username.options.required= true user.login.elements.username.options.filters.lower.filter= " Stringtolower ";
Password element user.login.elements.password.type= "password"
User.login.elements.password.options.validators.strlen.validator= "Stringlength" user.login.elements.password.options.validators.strlen.options.min= "6" user.login.elements.password.options.required= true; Submit element User.login.elements.submit.type= "Submit"

Next, you can pass it to the form constructor:

<?php
$config = Newzend_config_ini ($configFile, ' development ');
$form   = new Zend_form ($config->user->login);
? >

The entire form is defined.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.