Detailed explanation of Yii2 creation form (ActiveForm) method

高洛峰
Release: 2023-03-05 13:32:01
Original
1808 people have browsed it

The example in this article describes the method of creating a form (ActiveForm) in Yii2. I share it with you for your reference. The details are as follows:

Since the form involves some verification information and the attribute settings are many and complicated, please leave a message if there is anything incorrect.

Directory

Generation of form

Methods in the form
ActiveForm::begin() method
ActiveForm::end() method
getClientOptions() method
Other methods: errorSummary, validate, validateMultiple

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

Let’s first look at the simplest ones in Yii Let’s first have an intuitive understanding of the login form and the generated html code and interface

<?php $form = ActiveForm::begin([&#39;id&#39; => &#39;login-form&#39;]); ?>
  <?= $form->field($model, &#39;username&#39;) ?>
  <?= $form->field($model, &#39;password&#39;)->passwordInput() ?>
  <?= $form->field($model, &#39;rememberMe&#39;)->checkbox() ?>
  <div style="color:#999;margin:1em 0">
   If you forgot your password you can <?= Html::a(&#39;reset it&#39;, [&#39;site/request-password-reset&#39;]) ?>
  </div>
  <div class="form-group">
     <?= Html::submitButton(&#39;Login&#39;, [&#39;class&#39; => &#39;btn btn-primary&#39;, &#39;name&#39; => &#39;login-button&#39;]) ?>
  </div>
<?php ActiveForm::end(); ?>
Copy after login

The following is the generated form Html, and I have marked 5 parts in it.

1. Form generation

In Yii, the form is both ActiveForm and Widget. As you can see above, it starts with begin

<?php $form = ActiveForm::begin([&#39;id&#39; => &#39;login-form&#39;]); ?>
Copy after login

The middle is the input box for each item. Finally, it ends with end

<?php ActiveForm::end(); ?>
Copy after login

2. Methods in the form

In Widget, the begin() method will call the int method

public function init()
Copy after login

The last end() method will be called run method

public function run()
Copy after login

1、ActiveForm::begin() method

//这个是在执行 $form = ActiveForm::begin([&#39;id&#39; => &#39;login-form&#39;]); 中的begin方法的时候调用的
public function init()
{
    //设置表单元素form的id
    if (!isset($this->options[&#39;id&#39;])) {
      $this->options[&#39;id&#39;] = $this->getId();
    }
    //设置表单中间的要生成各个field的所使用的类
    if (!isset($this->fieldConfig[&#39;class&#39;])) {
      $this->fieldConfig[&#39;class&#39;] = ActiveField::className();
    }
    //这个就是输出表单的开始标签
    //如:<form id="login-form" action="/lulublog/frontend/web/index.php?r=site/login" method="post">
    echo Html::beginForm($this->action, $this->method, $this->options);
}
Copy after login


##2、ActiveForm::end() method

//这个是在执行 ActiveForm::end(); 中的end方法的时候调用的
public function run()
{
    //下面这个就是往视图中注册表单的js验证脚本,
    if (!empty($this->attributes)) {
      $id = $this->options[&#39;id&#39;];
      $options = Json::encode($this->getClientOptions());
      $attributes = Json::encode($this->attributes);
      $view = $this->getView();
      ActiveFormAsset::register($view);
      /*
       * $attributes:为要验证的所有的field数组。它的值是在activeform中创建field的时候,在field的begin方法中给它赋值的。
       * 其中每个field又是一个数组,为这个field的各个参数
       * 比如username的field中的参数有
       * validate、id、name、
       * validateOnChange、validateOnType、validationDelay、
       * container、input、error
       *
       * $options:为这个表单整体的属性,如:
       * errorSummary、validateOnSubmit、
       * errorCssClass、successCssClass、validatingCssClass、
       * ajaxParam、ajaxDataType
       */
      $view->registerJs("jQuery(&#39;#$id&#39;).yiiActiveForm($attributes, $options);");
    }
    //输出表单的结束标签
    echo Html::endForm();
}
Copy after login


##3. getClientOptions() method

/*
* 设置表单的全局的一些样式属性以及js回调事件等
*/
protected function getClientOptions()
{
    $options = [
      &#39;errorSummary&#39; => &#39;.&#39; . $this->errorSummaryCssClass,
      &#39;validateOnSubmit&#39; => $this->validateOnSubmit,
      &#39;errorCssClass&#39; => $this->errorCssClass,
      &#39;successCssClass&#39; => $this->successCssClass,
      &#39;validatingCssClass&#39; => $this->validatingCssClass,
      &#39;ajaxParam&#39; => $this->ajaxParam,
      &#39;ajaxDataType&#39; => $this->ajaxDataType,
    ];
    if ($this->validationUrl !== null) {
      $options[&#39;validationUrl&#39;] = Url::to($this->validationUrl);
    }
    foreach ([&#39;beforeSubmit&#39;, &#39;beforeValidate&#39;, &#39;afterValidate&#39;] as $name) {
      if (($value = $this->$name) !== null) {
        $options[$name] = $value instanceof JsExpression ? $value : new JsExpression($value);
      }
    }
    return $options;
}
Copy after login


Below This is the generated form validation Js code

jQuery(document).ready(function () {
    jQuery(&#39;#login-form&#39;).yiiActiveForm(
    {
        "username":{
            "validate":function (attribute, value, messages) {
                yii.validation.required(value, messages, {"message":"Username cannot be blank."});
            },
            "id":"loginform-username",
            "name":"username",
            "validateOnChange":true,
            "validateOnType":false,
            "validationDelay":200,
            "container":".field-loginform-username",
            "input":"#loginform-username",
            "error":".help-block"},
        "password":{
            "validate":function (attribute, value, messages) {
                yii.validation.required(value, messages, {"message":"Password cannot be blank."});
            },
            "id":"loginform-password",
            "name":"password",
            "validateOnChange":true,
            "validateOnType":false,
            "validationDelay":200,
            "container":".field-loginform-password",
            "input":"#loginform-password",
            "error":".help-block"
            },
        "rememberMe":{
            "validate":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,
            "validateOnType":false,
            "validationDelay":200,
            "container":".field-loginform-rememberme",
            "input":"#loginform-rememberme",
            "error":".help-block"}
    },
    {
        "errorSummary":".error-summary",
        "validateOnSubmit":true,
        "errorCssClass":"has-error",
        "successCssClass":"has-success",
        "validatingCssClass":"validating",
        "ajaxParam":"ajax",
        "ajaxDataType":"json"
    });
});
Copy after login


4. Other methods: errorSummary, validate, validateMultiple

public function errorSummary($models, $options = [])
Copy after login


It mainly summarizes all error information in the model into a div.

public static function validate($model, $attributes = null)
public static function validateMultiple($models, $attributes = null)
Copy after login


These two are methods of obtaining error information, which are relatively simple and I won’t go into details.

3. Parameters in the form

1. Properties of the form itself

$action: Set the url address submitted by the current form. If it is empty, it is the current url.

$method: Submission method, post or get, default is post

$option: Set other attributes of the form, such as id, etc. If the id is not set, a prefix with $autoIdPrefix will be automatically generated. The automatically added id

//这个方法在Widget基本中
public function getId($autoGenerate = true)
{
    if ($autoGenerate && $this->_id === null) {
      $this->_id = self::$autoIdPrefix . self::$counter++;
    }
    return $this->_id;
}
Copy after login


2. Attributes related to the input boxes of each item (field) in the form

Each field generated by Yii consists of 4 parts Composition:

① The outermost div is the container of each field,

② label is the text description of each field,

③ input is the input element,
④ and there is another div Prompt information for errors.

<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>
Copy after login


$fieldConfig: This is the attribute set by the unified configuration information of all fields. That is to say, the attributes in the field class can be set here.

public function field($model, $attribute, $options = [])
{
    //使用fieldConfig和options属性来创建field
    //$options会覆盖统一的fieldConfig属性值,以实现每个field的自定义
    return Yii::createObject(array_merge($this->fieldConfig, $options, [
      &#39;model&#39; => $model,
      &#39;attribute&#39; => $attribute,
      &#39;form&#39; => $this,
]));
}
Copy after login


About the attributes of verification:

① $enableClientValidation: Whether to verify on the client side, that is, whether to generate a front-end js verification script (if in the form If ajax verification is set, this js script will also be generated).

② $enableAjaxValidation: Whether it is ajax validation

③ $validateOnChange: Validate when the input box loses focus and the value changes
④ $validateOnType: Validate when input
⑤ $validationDelay: Verification delay time, unit is milliseconds

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

About the properties of each field container style:

$requiredCssClass: the style of required items, the default is 'required'

$errorCssClass: the style of verification errors, the default value is ' has-error'

$successCssClass: Verify the correct style, the default value is 'has-success'
$validatingCssClass: The style during the verification process, the default value is 'validating'

3, ajax Verification

$validationUrl: URL location for ajax verification

$ajaxParam: get parameter in the url, used to indicate that the current request is ajax, the default value is 'ajax'

$ajaxDataType: ajax request return Data format

4. Front-end js event attribute

$beforeSubmit: event before submitting the form. If false is returned, the form will not be submitted. The format is:

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


$beforeValidate: Triggered before each attribute is validated, the format is:

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


$afterValidate: After each attribute is validated Triggered, the format is:

function ($form, attribute, messages) {
}
Copy after login


5. Other attributes in the form

$validateOnSubmit: Verify when submitting the form

$errorSummary: Total The style of the error prompt

$attributes: This attribute is quite special. It is assigned in the field to the $attributes in this form when the field is created. This ensures that the input form generated through the field method can be verified

I hope this article will be helpful to everyone's PHP program design based on the Yii framework.

For more detailed explanations of Yii2 creation form (ActiveForm) methods and related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!