Home >Backend Development >PHP Tutorial >Detailed explanation of Yii2 creation form (ActiveForm) method
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(['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 you 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(); ?>
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(['id' => 'login-form']); ?>
The middle is the input box for each item. Finally, it ends with end
<?php ActiveForm::end(); ?>
2. Methods in the form
In Widget, the begin() method will call the int method
public function init()
The last end() method will be called run method
public function run()
1、ActiveForm::begin() method
//这个是在执行 $form = ActiveForm::begin(['id' => 'login-form']); 中的begin方法的时候调用的 public function init() { //设置表单元素form的id if (!isset($this->options['id'])) { $this->options['id'] = $this->getId(); } //设置表单中间的要生成各个field的所使用的类 if (!isset($this->fieldConfig['class'])) { $this->fieldConfig['class'] = 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); }
//这个是在执行 ActiveForm::end(); 中的end方法的时候调用的 public function run() { //下面这个就是往视图中注册表单的js验证脚本, 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:为要验证的所有的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('#$id').yiiActiveForm($attributes, $options);"); } //输出表单的结束标签 echo Html::endForm(); }
##3. getClientOptions() method
/* * 设置表单的全局的一些样式属性以及js回调事件等 */ 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; }
Below This 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 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" }); });
4. Other methods: errorSummary, validate, validateMultiple
public function errorSummary($models, $options = [])
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)
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; }
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>
$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, [ 'model' => $model, 'attribute' => $attribute, 'form' => $this, ])); }
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... }
$beforeValidate: Triggered before each attribute is validated, the format is:
function ($form, attribute, messages) { ...return false to cancel the validation... }
$afterValidate: After each attribute is validated Triggered, the format is:
function ($form, attribute, messages) { }
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!