How does Yii's activeform form tool work?

Source: Internet
Author: User
Keywords Yii2 activeform form

Problem:

Recently in the development with Yii, his form verification function is also very powerful, but found that this ActiveForm form tool does not come, who can help explain under, thank you!

Answer:

I don't know if the main problem is a simple application scenario. Sunglass (▔,▔) deny
I'm going to give you a super-super-simple. • User comments • Examples of form submissions:

As @ The flowers said, ActiveForm to use with the Model/activerecord.
So get a table like this first, ↓

+----------+--------------+------+-----+---------+----------------+| Field    | Type         | Null | Key | Default | Extra          |+----------+--------------+------+-----+---------+----------------+| ID       | int      | NO   | PRI | NULL    | auto_increment | | username | varchar |  NO   |     | NULL    |                | | comment  | text         | NO   |     | NULL    |                | | add_time | datetime     | YES  |     | NULL    |                | | gender   | tinyint (3)   | YES  |     | NULL    |                | +----------+--------------+------+-----+---------+----------------+

With the table, we build the model, and here I directly use the GII scaffold to generate a model named Comments.

Information needed in the form:
1. User name (varchar type data)
2. Comment Content (text type data)
3. Gender (int type data)

I want to at least write this in your controller's action:

/*action*/$model = new Comments (); Instantiate Comments Modelreturn $this->render (' msg ', [' model ' = ' $model]); Push the comments model as a parameter The view page I want

The "msg" in render is the corresponding view page

Then take a look at the msg view:
In the MSG view, most of the methods and properties we commonly use are contained in two key classes, namely yii\helpers\html and Yii\bootstrap\activeform, which are responsible for the method of common Html tags and are convenient for unification. The latter is our protagonist ActiveForm. To make the code in the form simple and readable, let's add a reference to the view header:

<!--msg.php file--><?phpuse yii\helpers\html;use yii\bootstrap\activeform;? >

Common Forms we use <form>...</form> as the beginning and the end, ActiveForm also, just change a more cool method:

<!--msg.php file--<?php $form = Activeform::begin ([...]);? > ...    ...    ... <?php activeform::end ();? >

ActiveForm is the structure! (≖‿≖) The ellipsis in ✧,begin is the parameter we want to configure, and we'll replace him later.
First look at the form to fill in the entry:

<!--msg.php file--><?= $form->field ($model, ' username ')->textinput (); User name input box? ><?= $form->field ($model, ' comment ')->textarea (); Comment content input box? ><?= $form->field ($model, ' Gender ')->radiolist ([' 1 ' = ' men ', ' 2 ' = ' women '])->label (' sex '); Sex selection Box?>

Yes, just one line.
One line, because field automatically helps you pack (a default label,1 default input,1 default error hint).
The parameters you need to provide are
1. The comments model we are moving from action.
The attributes in 2.model (the fields in the corresponding table).
Where is the label read from? The attributelabels in Comments model.
Where does the error display rule come from? The rules rule validation in the Comments model.

Field ($model, ' xxx ')

What's in the back?
That's the type of input box to choose from.
The field () method of the ActiveForm, which returns a result based on the model and model attributes you have given.
The method followed by the Activefield object, field (), is to choose the type of input box according to your needs, as well as some custom configurations.
Take the chestnut above gender:
If this is the case, then it will return to me a default textinput input box, so I added->radiolist ([' 1 ' = ' man ', ' 2 ' = ' women ']) and changed TextInput to a radio single box, The array in Radiolist is the value and label of the corresponding option. ->label (' sex '), I don't think I want to translate the attributes written in Comments model, so I've rewritten the label as well.

With the input entry, the next step is the Submit button:

<!--msg.php file--><?= html::submitbutton (' comment ', [' class ' = ' btn btn-primary ', ' name ' = ' Submit-button ') ])?>

The first parameter is the text of the button you want to display, the second array is also configured, adding the button's class and name.

Then go back to Activeform::begin ([...]) method, look at the general parameter configuration in begin:

[    ' id ' = ' msg-form ',    ' options ' = [' class ' = ' Form-horizontal '],    ' enableajaxvalidation ' False,    ' fieldconfig ' = [                ' template ' = ' = ' {label}\n<p class=\ ' col-lg-3\ ' >{input}</p>\n< P class=\ "col-lg-8\" >{error}</p> ",                ' labeloptions ' = [' class ' = ' col-lg-1 Control-label '],    ]

1. The ID of the form form, in 'id'=>'msg-form' addition to the role of the unique identifier, if you turn on the form asynchronous rule validation, this will also be submitted as the $_post[ajax] parameter to the action.
2. 'options' => ['class'=>'form-horizontal'] add some attributes to the form
3. 'enableAjaxValidation'=>false This is the "whether asynchronous authentication" configuration. In fact, it is false by default, can not be listed, it is listed here is necessary to know the existence of this property, because in the complex form is generally set to true. Also, in your action, increase the method for asynchronous validation.
4. 'fieldConfig' Configure the Activefield object that will be generated in the form, which is configured in the input entry, and this is the unified configuration.
' Template ' = ' {label}\n

{input}

\ n

{Error}

", as the name implies, template. This means that an input box plan (LABEL+INPUT+ERROR) is displayed in the style I want. If not set, Yii will use the default template "{Label}\n{input}\n{hint}\n{error}" (Too Ugly (' ・д・´)). ' Labeloptions ' = [' class ' = ' col-lg-1 Control-label '] is the addition of the {label} attribute in the package (to beautify the style).

Here's what the whole msg.php looks like:

<!--msg.php--><?phpuse yii\helpers\html;use yii\bootstrap\activeform;? ><p class= "Container" ><!--start Handsome form components--<?php $form = Activeform::begin ([' id ' + ' m            Sg-form ', ' options ' = [' class ' = ' form-horizontal '], ' enableajaxvalidation ' =>false, ' Fieldconfig ' = [' template ' = ' = ' {label}\n<p class=\ ' col-lg-3\ ' >{input}</p>\n<p            Class=\ "col-lg-8\" >{error}</p> ", ' labeloptions ' = [' class ' = ' col-lg-1 Control-label '],    ]    ]); ?><!--Form Entries--<?= $form->field ($model, ' username ')->textinput ();?> <?= $form->field ($mod El, ' comment ')->textarea ()?> <?= $form->field ($model, ' Gender ')->radiolist ([' 1 ' = ' male ', ' 2 ' = ' = ') Female '])->label (' sex ');?><!--submit button--<p class= "Form-group" > <p class= "col-lg-offset-1 col-lg-11 "> <?= Html::submitbutton (' comment ', [' Class ' = ' btn btn-primary ', ' name ' = ' Submit-button '])?> </p> </p><!--end handsome form components--&gt    ; <?php activeform::end ();? ></p>

Here, if you click Submit, the post content will be the same

    [_CSRF] = rhfotmg1tupwnx0skq0cenq/es8uqym9hhicfhbxhnm1qhqelnr9ba==    [Comments] = = Array        (            [ Username] = Cookedsteak            [Comment] = Here comes the comment!            [Gender] + 2        )    [ajax] = Msg-form    [Submit-button] = undefined

This is followed by handling your data in action, as you want.

The above is a personal understanding of the activeform, there may be some places too simple, only hope to help the same beginner yiier (づ ̄³ ̄) Old

  • 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.