The example in this article describes the method that Yii2 creates a form (ActiveForm). Share to everyone for your reference, specific as follows:
Because the form involves some authentication aspect information, the attribute setting is more and more complex, so where there is any incorrect place please leave a message
Directory
Form generation
Methods in the form
Activeform::begin () method
Activeform::end () method
Getclientoptions () method
Other methods: Errorsummary, validate, Validatemultiple
Parameters in a form
Properties of Form form itself
Properties related to individual item (field) input boxes in a form
$fieldConfig
About validation Properties
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 forms in Yii and the generated HTML code and interface, 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 with 5 parts.
1. Form generation
In Yii the form is also a widget, which can be seen from begin ActiveForm.
<?php $form = Activeform::begin ([' id ' => ' login-form ']);?>
An input box for each item in the middle, ending with end
<?php activeform::end ();?>
2, the form of the method
The Begin () method in the widget calls the Int method
The last End () method calls the Run method
1, Activeform::begin () method
This is in the execution $form = Activeform::begin ([' id ' => ' login-form ']); The Public
function init ()
{
//Set the ID
if (!isset ($this->options[' id ') of the table cell form) is invoked when the Begin method in the
$this->options[' id '] = $this->getid ();
}
Sets the class that is used in the middle of the form to generate each field
if (!isset ($this->fieldconfig[' class ')) {
$this->fieldconfig[' class '] = Activefield::classname ();
}
This is the start tag of 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 the public function run () that is invoked when executing the End method in Activeform::end (); The following is a JS validation script that registers 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 the field when the field is created in ActiveForm. * Each field is an array, and the parameters for this field are * Validate, ID, name, * validateonchange, valida, username field Teontype, Validationdelay, * container, INPUT, Error * * $options: For the overall properties of this form, such as: * Errorsummary, V
Alidateonsubmit, * errorcssclass, Successcssclass, Validatingcssclass, * ajaxparam, Ajaxdatatype * *
$view->registerjs ("# $id '). Yiiactiveform ($attributes, $options);");
//Output form end tag echo html::endform (); }
3, Getclientoptions () method
* * Set some of the global style properties of the form and JS callback event, etc.
/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": {"Val Idate ": Function (attribute, value, messages) {yii.validation.required (value, messages, {" Message ":" Userna Me cannot be blank.});}, "id": "loginform-username", "name": "Username", " Validateonchange ": True," Validateontype ": false," Validationdelay ":" Container ":". F Ield-loginform-username "," Input ":" #loginform-username "," Error ":". Help-block "}," password ": {" Validate ": function (attribute, value, messages) {yii.validation.required (value, messages
, {"Message": "Password cannot is blank."});
}, "id": "Loginform-password", "name": "Password", "Validateonchange": true, "Validateontype": false, "Validationdelay": "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 is either \ 1\" or "0\". "
, "Skiponempty": 1}); }, "id": "loginform-rememberme", "name": "RememberMe", "Validateonchange": true, "validate Ontype ": false," Validationdelay ":" Container ":". Field-loginform-rememberme "," Inpu
T ":" #loginform-rememberme "," Error ":". Help-block "}}, {" Errorsummary ":". Error-summary ", "Validateonsubmit": True, "Errorcssclass": "Has-error", "Successcssclass": "Has-success", "Valida
Tingcssclass ":" Validating "," Ajaxparam ":" Ajax "," Ajaxdatatype ":" JSON "});
});
4. Other methods: Errorsummary, validate, Validatemultiple
Public Function Errorsummary ($models, $options = [])
It is mainly to bring all the error information in model into a div.
public static function Validate ($model, $attributes = null) public
static function Validatemultiple ($models, $ attributes = null)
These two are the ways to get the wrong message, simpler and more simple.
3, the form of the parameters
1. The properties of form form itself
$action: Sets the URL address of the current form submission, if NULL is the current URL
$method: Submit method, post or get, default to post
$option: This inside sets the other properties of the form, such as ID, and if no ID is set, an automatically incremented ID with $autoidprefix prefix will be generated automatically
This method is in the widget base public
function GetId ($autoGenerate = True)
{
if ($autoGenerate && $this->_id = = = null) {
$this->_id = self:: $autoIdPrefix. Self:: $counter + +;
return $this->_id;
}
2. Properties related to each item (field) input box in a form
Each field generated by Yii consists of 4 parts:
① the outermost div is the container for each field,
②label is a textual description of each field,
③input is the INPUT element,
④ also has 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 property of all the field's unified configuration information settings. This means that the properties in the field class can be set here.
The Public function field ($model, $attribute, $options = [])
{
//Use the Fieldconfig and Options properties to create a field
//$ The options override the uniform Fieldconfig property values to implement the custom return Yii::createobject (Array_merge for each field (
$this->fieldconfig, $ Options, [
' model ' => $model,
' attribute ' => $attribute,
' form ' => $this,
]);
}
About validation Properties:
① $enableClientValidation: Whether in the client-side validation, that is, whether to generate front-end JS verification script (if the form is set up AJAX validation, will also generate this JS script).
② $enableAjaxValidation: Whether it is an AJAX validation
③ $validateOnChange: Validating when the input box loses focus and the value changes
④ $validateOnType: Validate when you are typing
⑤ $validationDelay: Time to verify the delay, in milliseconds
These 5 properties can be set individually when each field is created, because there are 5 properties in the field class.
About the properties of each field container style:
$requiredCssClass: Required style, default to ' required '
$errorCssClass: Validation of the wrong style with the default value ' 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: The URL where Ajax validates
$ajaxParam: A get parameter in the URL that indicates the current AJAX request, with the default value ' Ajax '
$ajaxDataType: Data format returned by Ajax request
4, front-end JS event properties
$beforeSubmit: The event before the form is submitted, and if False, the form will not be submitted, in the form:
function ($form) {
... return false to cancel submission ...
}
$beforeValidate: Fires before each property is validated, in the form:
function ($form, attribute, messages) {
... return false to cancel the validation ...
}
$afterValidate: Triggered after each property is validated, in the form:
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 is a special attribute that is assigned to the $attributes in this form in field when the field is created. This ensures that input forms generated through the field method can be validated
For more information on YII-related content, readers who are interested in this site can view the topics: Introduction to YII Framework and summary of common skills, "Summary of PHP Excellent development framework", "Smarty Template Introductory Course", "Introduction to PHP object-oriented programming", "PHP string" Summary of Usage , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"
I hope this article will help you with the PHP program design based on the YII framework.