Yii Framework official guide series 21-use forms: use Form Builder (CForm)

Source: Internet
Author: User
When creating HTML forms, we often find that we are writing a lot of repetitive view code that is difficult to reuse in different projects. For example, for each input box, we need to associate it with a text tag and display possible verification errors ....



When creating HTML forms, we often find that we are writing a lot of repetitive view code that is difficult to reuse in different projects. For example, for each input box, we need to associate it with a text tag and display possible verification errors. To improve the reusability of these codes, we can use form generator features available in version 1.1.0.

1. Basic concepts

Yii form builder uses the CForm object to represent the content required to describe an HTML form, including the data models associated with the form, the input boxes in the form, and how to render the entire form. Developers mainly need to create and configure the CForm object, and then call its rendering method to display the form.

The input box parameters of a form are organized into layers based on the form elements. At the top layer of the structure, it is a CForm object. The members of this object are divided into two categories: CForm: buttons and CForm: elements. The former contains button elements (such as the submit button and reset button), and the latter contains input elements, static text, and child forms. The child form is also a CForm object, but it exists in the CForm: elements of another form. Child forms can have their own data models, CForm: buttons and CForm: elements sets.

When a user submits a form, the data entered in the entire form structure is submitted and contains the data entered in the subform. CForm provides a convenient way to automatically assign values to the input data to corresponding data attributes and perform data verification.

2. create a simple form

Next, we will show you how to use the form builder to create a logon form.

First, write the login action code:


public function actionLogin(){    $model = new LoginForm;    $form = new CForm('application.views.site.loginForm', $model);    if($form->submitted('login') && $form->validate())        $this->redirect(array('site/index'));    else        $this->render('login', array('form'=>$form));}

In the above code, we use the path aliasapplication.views.site.loginForm(Will be briefly explained) the specified parameter creates a CForm object. CForm object andLoginFormAssociate a Model (introduced in Creating Model.

As shown in the code, if the form is submitted and all input is verified without errors, we will go to the user's browsersite/indexPage. Otherwise, we use this form for rendering.loginView.

Path aliasapplication.views.site.loginFormActually refers to PHP filesprotected/views/site/loginForm.php. This file should return a PHP array, which represents the configuration required by CForm, as shown below:


return array(    'title'=>'Please provide your login credential',    'elements'=>array(        'username'=>array(            'type'=>'text',            'maxlength'=>32,        ),        'password'=>array(            'type'=>'password',            'maxlength'=>32,        ),        'rememberMe'=>array(            'type'=>'checkbox',        )    ),    'buttons'=>array(        'login'=>array(            'type'=>'submit',            'label'=>'Login',        ),    ),);

Configuration is an associated array composed of key-value pairs. it is used to initialize the corresponding attributes of CForm. The most important attribute to be configured, as described earlier, is CForm: elements and CForm: buttons. Each of them is an array that specifies the list of form elements. In the subsequent sections, we will provide more details about how to configure form elements.

Finally, we compileloginView, which can be concise as follows,


Login

Tip:The above codeecho $form;Equivalentecho $form->render();. This is because CForm is executed.__toStringMagic method, which callsrender()And return the result as a string representing the form object.

3. specify the form element

Using Form Builder, most of our work is changed from writing View script code to specifying form elements. This section describes how to specify the CForm: elements attribute. We do not want to describe CForm: buttons because its configuration is almost the same as that of CForm: elements.

The CForm: elements attribute accepts an array as its value. Each array element specifies a separate form element, which can be an input box, a static text string, or a subform.

Specify input element

An input element consists of tags, input boxes, prompt text, and error display. It must be associated with a model property. The type of an input element is represented as a CFormInputElement instance. The following code in the CForm: elements array specifies a separate input element:


'username'=>array(    'type'=>'text',    'maxlength'=>32,),

It indicates that the model attribute is namedusernameThe type of the input box istext, ItsmaxlengthThe property is 32.

Any writable attributes of CFormInputElement can be configured as above. For example, you can specify the hint option to display the prompt information, or you can specify the items option. if the input box is a list box, a drop-down list, a multiple-choice list, or a single-choice button list. If the option name is not a CFormInputElement attribute, it is considered to be an attribute corresponding to the HTML input element, for example, becausemaxlengthNot a CFormInputElement attribute, it is rendered as an HTML text input boxmaxlengthAttribute.

Pay special attention to the type option. It specifies the type of the input box. For example,textType means that a common text input box will be rendered;passwordType indicates that a password input box is rendered. CFormInputElement identifies the following built-in types:

  • Text

  • Hidden

  • Password

  • Textarea

  • File

  • Radio

  • Checkbox

  • Listbox

  • Dropdownlist

  • Checkboxlist

  • Radiolist

In the above built-in types, we want to talk more about the usage of these "list" types, includingdropdownlist,checkboxlistAndradiolist. For these types, you must set the items attribute of the corresponding input element. You can do this:


'gender'=>array(    'type'=>'dropdownlist',    'items'=>User::model()->getGenderOptions(),    'prompt'=>'Please select:',),...class User extends CActiveRecord{    public function getGenderOptions()    {        return array(            0 => 'Male',            1 => 'Female',        );    }}

The above code will generate a drop-down list selector, prompting that the text is "please select :". Options include "Male" and "Female", which areUserIn the model classgetGenderOptionsMethod.

In addition to these built-in types, the type option can also be a widget class name or the path alias of the widget class. The widget class must be extended from CInputWidget or CJuiInputWidget. When an input element is rendered, an instance of the specified widget class is created and rendered. The widget will be configured using the specification as given for the input element.

Static text

In many cases, a form contains decorative HTML code. For example, a horizontal line is used to separate different parts of a form. an image appears at a specific position to enhance the visual appearance of the form. You can specify these HTML codes as static text in the CForm: elements set. To do this, we only need to specify a static text string as an array element at the appropriate position of CForm: elements. For example,


return array(    'elements'=>array(        ......        'password'=>array(            'type'=>'password',            'maxlength'=>32,        ),        '
 ',        'rememberMe'=>array(            'type'=>'checkbox',        )    ),    ......);

In the above, wepasswordInput box andrememberMeInsert a horizontal line between them.

Static text is best used when the text content and their locations are irregular. If each input element in a form needs to be decorated similarly, we should customize the form rendering method, which will be briefly described in this section.

Subtable

A child form is used to separate a long form from several logical parts. For example, we can separate the user registry form into two parts: logon information and archive information. Each subform can be associated with a data model. For example, in the user registration form, if we store the user login information and file information to two separate data tables (represented as two data models ), then, each subform needs to be associated with a corresponding data model. If we store all the information in a data table, no data model is available for any subforms because they share the same model as the root form.

A child form is also represented as a CForm object. To specify a child form, we should configure the CForm: elements attribute to a type that isformElements:


return array(    'elements'=>array(        ......        'user'=>array(            'type'=>'form',            'title'=>'Login Credential',            'elements'=>array(                'username'=>array(                    'type'=>'text',                ),                'password'=>array(                    'type'=>'password',                ),                'email'=>array(                    'type'=>'text',                ),            ),        ),        'profile'=>array(            'type'=>'form',            ......        ),        ......    ),    ......);

Similar to configuring a root form, we need to specify the CForm: elements attribute for a subform. If a child form needs to be associated with a data model, we can also configure its CForm: model attribute.

Sometimes, we want to use a class to represent the form, instead of the default CForm class. For example, this section will briefly show you how to extend the CForm to customize the form rendering logic. Specify the input element typeformA child form is automatically represented as an object, and its class is the same as its parent form. If we specify that the input element type is similarXyzForm(FormAnd then the child form is represented asXyzFormObject.

4. access form elements

The access form element is as simple as the access array element. The CForm: elements property returns a CFormElementCollection object that extends from CMap and allows access to its elements in a way similar to a common array. For example, to access the elements in the login formusername, We can use the following code:


$username = $form->elements['username'];

To accessemailElement, use


$email = $form->elements['user']->elements['email'];

Because CForm executes array access for its CForm: elements attribute, the above code can be simplified:


$username = $form['username'];$email = $form['user']['email'];

5. create a nested form

We have already described the child form. We call a form with subforms as a nested form. In this section, we use the user registry form as an example to demonstrate how to create a nested form that associates multiple data models. Assume that the user authentication information is stored asUserModel, and the user's archive information is stored asProfileModel.

First, createregisterThe action is as follows:


public function actionRegister(){    $form = new CForm('application.views.user.registerForm');    $form['user']->model = new User;    $form['profile']->model = new Profile;    if($form->submitted('register') && $form->validate())    {        $user = $form['user']->model;        $profile = $form['profile']->model;        if($user->save(false))        {            $profile->userID = $user->id;            $profile->save(false);            $this->redirect(array('site/index'));        }    }    $this->render('register', array('form'=>$form));}

In the above, we useapplication.views.user.registerFormThe specified configuration creates a form. After the form is submitted and verified, we try to save the user and pro role le models. We accessmodelAttribute to retrieve the user and pro role le models. Because the input verification has been completed, we call$user->save(false)To skip verification. This is also true for the pro role model.

Next, we will compile the form configuration file.protected/views/user/registerForm.php:


return array(    'elements'=>array(        'user'=>array(            'type'=>'form',            'title'=>'Login information',            'elements'=>array(                'username'=>array(                    'type'=>'text',                ),                'password'=>array(                    'type'=>'password',                ),                'email'=>array(                    'type'=>'text',                )            ),        ),        'profile'=>array(            'type'=>'form',            'title'=>'Profile information',            'elements'=>array(                'firstName'=>array(                    'type'=>'text',                ),                'lastName'=>array(                    'type'=>'text',                ),            ),        ),    ),    'buttons'=>array(        'register'=>array(            'type'=>'submit',            'label'=>'Register',        ),    ),);

In the preceding example, when specifying each subform, we also specify its CForm: title attribute. The default form rendering logic encapsulates each sub-form into one eld-set and uses this attribute as its title.

Finally, we compileregisterView script:


Register

6. Custom form Display

The main benefit of using Form builder is the separation of logic (form configuration is stored in a separate file) and representation (CForm: render method. In this way, we can customize the form display by rewriting CForm: render or providing a partial view to render the form. Both methods can maintain the integrity of form configuration and can be easily reused.

When rewriting CForm: render, you need to traverse CForm: elements and CForm: buttons and call the CFormElement: render Method of each form element. For example,


class MyForm extends CForm{    public function render()    {        $output = $this->renderBegin();        foreach($this->getElements() as $element)            $output .= $element->render();        $output .= $this->renderEnd();        return $output;    }}

We may also need to write a View script._formTo render a view:


 renderBegin();foreach($form->getElements() as $element)    echo $element->render();echo $form->renderEnd();

To use this view script, we need to call:


$this->renderPartial('_form', array('form'=>$form));

If a common form rendering is not applicable to a special form (for example, a form requires irregular decoration for a specific element), we can do this in the view script:


some complex UI elements here
 some complex UI elements here
 some complex UI elements here

In the final method, the form builder does not seem to be helpful because we still need to write a lot of form code. However, it is still advantageous that the form is specified using a separate configuration file, which can help developers focus more on the logic part.

The above is the Yii Framework official guide series 21-use form: use Form Builder (CForm) content. For more information, see PHP Chinese network (www.php1.cn )!

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.