Yii2 Creating a form (ActiveForm) method

Source: Internet
Author: User
The example in this article describes how Yii2 creates a form (ActiveForm). Share to everyone for your reference, as follows:

Because the form involves some verification aspects of information, property settings are more and more complex, so where there is any incorrect place please leave a message pointing

Directory

Form generation

Methods in the form
Activeform::begin () method
Activeform::end () method
Getclientoptions () method
Other methods: Errorsummary, validate, Validatemultiple

Parameters in the form
Properties of Form form itself
Properties related to individual item (field) input boxes in the form
$fieldConfig
About the properties of validation
About the properties of each field container style
Ajax validation
Front-end JS Event
Other properties in the form

Let's take a look at the simplest login form in Yii and the generated HTML code and interface, first with an intuitive understanding

<?php $form = Activeform::begin ([' id ' = ' login-form '])?>  <?= $form->field ($model, ' username ')? >  <?= $form->field ($model, ' password ')->passwordinput ()?>  <?= $form->field ($model, ' RememberMe ')->checkbox ()?>  <div style= "color: #999; margin:1em 0" >   If you forgot your password Can <?= html::a (' Reset it ', [' Site/request-password-reset '])?>  </div>  <div class= "Form-group ">     <?= Html::submitbutton (' Login ', [' class ' = ' btn ' btn-primary ', ' name ' = ' Login-button '])?>  </div><?php activeform::end ();?>

Here is the generated form HTML, which I marked in 5 parts.

1. Form generation

In Yii, forms, ActiveForm, are also widgets, which can be seen as starting from begin

<?php $form = Activeform::begin ([' id ' = ' login-form ']);?>

The middle is the input box for each item and ends with end

<?php activeform::end ();?>

2. Methods in the form

The Begin () method in the widget calls the Int method

Public Function init ()

The last End () method calls the Run method

Public Function Run ()

1. Activeform::begin () method

This is performed $form = Activeform::begin ([' id ' = ' login-form ']); The Begin method in the call of the public function init () {    //sets the ID of the table cell form    if (!isset ($this->options[' id '))) {      $this- >options[' id '] = $this->getid ();    }    Set the class if (!isset ($this->fieldconfig[' class ')) in the middle of the form to be used to generate each field    {      $this->fieldconfig[' class '] = Activefield::classname ();    }    This is the start tag for the output form    //such as: <form id= "Login-form" action= "/lulublog/frontend/web/index.php?r=site/login" method= " Post ">    echo html::beginform ($this->action, $this->method, $this->options);}


2. Activeform::end () method

This is in the execution of Activeform::end (); When the end method is called the public Function run () {    ///below This is the JS verification script for registering the form in the view,    if (!empty ($this->attributes)) {      $id = $ this->options[' id '];      $options = Json::encode ($this->getclientoptions ());      $attributes = Json::encode ($this->attributes);      $view = $this->getview ();      Activeformasset::register ($view);       /* * $attributes: For all field arrays to be validated. Its value is assigned to it in the Begin method of field when the field is created in ActiveForm.       * Each field is an array, for each parameter of the field       * such as username field parameters are       * Validate, ID, name,       * Validateonchange , Validateontype, Validationdelay,       * container, input, error       *       $options: Attributes for this form as a whole, such as:       * Errorsummary, Validateonsubmit,       * errorcssclass, Successcssclass, Validatingcssclass,       * Ajaxparam, Ajaxdatatype       */      $view->registerjs ("JQuery (' # $id '). Yiiactiveform ($attributes, $options);");    }    End tag for output form    echo Html::endform ();}


3. Getclientoptions () method

/** set some of the global style properties of the form and the JS callback event, such as */protected function Getclientoptions () {    $options = [      ' errorsummary ' = '. '. $ This->errorsummarycssclass, '      validateonsubmit ' = $this->validateonsubmit,      ' Errorcssclass ' $this->errorcssclass,      ' successcssclass ' =-$this->successcssclass,      ' validatingcssclass ' = ' $ ' This->validatingcssclass,      ' ajaxparam ' = $this->ajaxparam,      ' Ajaxdatatype ', $this Ajaxdatatype,    ];    if ($this->validationurl!== null) {      $options [' validationurl '] = url::to ($this->validationurl);    }    foreach ([' Beforesubmit ', ' beforevalidate ', ' aftervalidate '] as $name) {      if (($value = $this, $name)!== null) {
   $options [$name] = $value instanceof jsexpression? $value: New Jsexpression ($value);      }    }    return $options;}


The following is the generated form validation JS code

jquery (document). Ready (function () {jQuery (' #login-form '). Yiiactiveform ({"username": {"Validate ": function (attribute, value, messages) {yii.validation.required (value, messages, {" Message ":" Username can Not being blank. "}", "id": "loginform-username", "name": "username", "Validateon Change ": True," Validateontype ": false," Validationdelay ": $," container ":". Field-loginfor M-username "," Input ":" #loginform-username "," Error ":". Help-block "}," password ": {" Validate ": Function (attribute, value, messages) {yii.validation.required (value, messages, {" Message ":" Pass Word cannot be blank. "}", "id": "Loginform-password", "name": "Password", "va Lidateonchange ": True," Validateontype ": false," Validationdelay ": $," container ":". field-    Loginform-password ",        "Input": "#loginform-password", "Error": ". Help-block"}, "RememberMe": {"VA                    Lidate ": Function (attribute, value, messages) {Yii.validation.boolean (value, messages, {            "TrueValue": "1", "Falsevalue": "0", "message": "Remember Me must be either \" 1\ "or \" 0\ ".", "Skiponempty": 1}); }, "id": "loginform-rememberme", "name": "RememberMe", "Validateonchange": true, "Validateont Ype ": false," Validationdelay ": $," container ":". Field-loginform-rememberme "," Input ":" #l Oginform-rememberme "," Error ":". Help-block "}}, {" Errorsummary ":". Error-summary "," Validat Eonsubmit ": True," Errorcssclass ":" Has-error "," Successcssclass ":" Has-success "," Validatingcssclass ":" Validating "," Ajaxparam ":" Ajax "," Ajaxdatatype ":" JSON "});


4, Other methods: Errorsummary, validate, Validatemultiple

Public Function Errorsummary ($models, $options = [])


It basically is to summarize all the error information in the model into a div.

public static function Validate ($model, $attributes = null) public static function Validatemultiple ($models, $attributes = Null


These two are the methods to get the error message, and it's easier to say nothing.

3. Parameters in the form

1. Form's own properties

$action: Sets the URL address of the current form submission, or the current URL if it is empty
$method: Submit method, post or get, default to post
$option: This inside sets the other properties of the form, such as ID, if not set ID, will automatically generate a $autoidprefix prefix automatically added ID

This method is in the Widget basic public function getId ($autoGenerate = True) {    if ($autoGenerate && $this->_id = = = null) { c1/> $this->_id = self:: $autoIdPrefix. Self:: $counter + +;    }    return $this->_id;}


2. Properties related to the field input box in the form

Each field generated by Yii consists of 4 parts:

① the outermost div for each field container,
②label for each field's text description,
③input is the INPUT element,
④ also has a div for the error message.

<div class= "Form-group field-loginform-username required Has-error" >    <label class= "Control-label" for= " Loginform-username ">Username</label>    <input type=" text "id=" Loginform-username "class=" Form-control "Name=" Loginform[username] ">    <div class=" Help-block ">username cannot be blank.</div ></div>


$fieldConfig: This is the property of all the field's unified configuration information settings. This means that the properties in the field class can be set here.

Public function field ($model, $attribute, $options = []) {    //Use Fieldconfig and Options properties to create field    //$ The options override the unified Fieldconfig property value to implement custom return yii::createobject for each field    (Array_merge ($this->fieldconfig, $ Options, [      ' model ' = $model,      ' attribute ' = ' $attribute,      ' form ' = ' $this,] ');}


About the properties of validation:

① $enableClientValidation: Whether or not to generate a front-end JS verification script on the client side (if AJAX validation is set in the form, this JS script will also be generated).
② $enableAjaxValidation: Whether it is AJAX authentication
③ $validateOnChange: Verify when the input box loses focus and the value changes
④ $validateOnType: Validate when you are typing
⑤ $validationDelay: Time to verify delay in milliseconds

These 5 properties can all be set individually when creating each field, as there are 5 properties in the field class.

About the properties of each field container style:

$requiredCssClass: The style of the required item, default to ' required '
$errorCssClass: The style of the validation error, the default value is ' Has-error '
$successCssClass: Verify the correct style, the default value is ' Has-success '
$validatingCssClass: The style in the validation process, the default value is ' validating '

3. Ajax Verification

$VALIDATIONURL: URL Place for AJAX authentication
$ajaxParam: The get parameter in the URL to indicate that the current AJAX request, the default value is ' Ajax '
$ajaxDataType: The data format returned by the AJAX request

4. Front-End JS event Properties

$beforeSubmit: Before the form is submitted, the form is not submitted if it returns false, in the form:

function ($form) {... return false to cancel submission ...}


$beforeValidate: Triggered before each property is validated, in the format:

function ($form, attribute, messages) {... return false to cancel the validation ...}


$afterValidate: After each property is triggered after validation, the format is:

function ($form, attribute, messages) {}


5. Other properties in the form

$validateOnSubmit: Validate when submitting a form
$errorSummary: The style of the total error hint place
$attributes: This property is special, and it is assigned to the $attributes of the form in field when the field is created. This ensures that the input forms generated by the field method can be validated

Hopefully this article will help you with the PHP program based on the YII framework.

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.