The example in this article describes the method of creating a form (ActiveForm) in Yii2. Share it with everyone for your reference, the details are as follows:
Since the form involves some verification information and has many and complex attribute settings, please leave a message to point out if there is anything incorrect.
Table of Contents
Generation of form
Methods in forms
ActiveForm::begin() method
ActiveForm::end() method
getClientOptions() method
Other methods: errorSummary, validate, validateMultiple
Parameters in the form
The properties of the form itself
Attributes related to the input boxes of each field in the form
$fieldConfig
About the attributes of verification
About the attributes of each field container style
ajax verification
Front-end js events
Other attributes in the form
Let’s first take a look at the simplest login form in Yii and the generated html code and interface to have 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 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, I have marked 5 parts in it.
1. Form generation
In Yii, a form is both an ActiveForm and a 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, and 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 run method will be called in the final end() 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); }
2. ActiveForm::end() method
//这个是在执行 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; }
The following is the generated form verification 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 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 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 of the current form submission, if it is empty, it is the current url
$method: submission method, post or get, default is post
$option: This sets other attributes of the form, such as id, etc. If the id is not set, an automatically increased id prefixed with $autoIdPrefix will be automatically generated
//这个方法在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 field in the form
Each field generated by Yii consists of 4 parts:
① The outermost div is the container of each field,
② label is the text description of each field,
③ input is the input element,
④ There is also a div for 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 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 properties of verification:
① $enableClientValidation: Whether to verify on the client side, that is, whether to generate a front-end js verification script (if ajax verification is set in the form, this js script will also be generated).
② $enableAjaxValidation: Whether it is ajax verification
③ $validateOnChange: Validate when the input box loses focus and the value changes
④ $validateOnType: Validate while typing
⑤ $validationDelay: Validation delay time, unit is milliseconds
These 5 attributes can be set individually when creating each field, because there are these 5 attributes in the field class.
About the attributes of each field container style:
$requiredCssClass: style of required items, default is ‘required’
$errorCssClass: Verification error style, default value is ‘has-error’
$successCssClass: Verify the correct style, the default value is 'has-success'
$validatingCssClass: style during the validation process, the default value is 'validating'
3. ajax verification
$validationUrl: URL for ajax verification
$ajaxParam: The get parameter in the url is used to indicate that the current request is an ajax request. The default value is ‘ajax’
$ajaxDataType: Data format returned by ajax request
4. Front-end js event attributes
$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:在每个属性在验证之后触发,格式为:
function ($form, attribute, messages) { }
5、表单中的其它属性
$validateOnSubmit:提交表单的时候进行验证
$errorSummary:总的错误提示地方的样式
$attributes:这个属性比较特殊,它是在创建field的时候,在field中为这个form中的$attributes赋值的。这样可以确保通过field方法生成的输入表单都可以进行验证
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。