Home Backend Development PHP Tutorial Detailed explanation of Yii2 creation form (ActiveForm) method_php example

Detailed explanation of Yii2 creation form (ActiveForm) method_php example

Aug 04, 2016 am 08:56 AM
yii2

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

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

Copy after login

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

<&#63;php $form = ActiveForm::begin(['id' => 'login-form']); &#63;>

Copy after login

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

<&#63;php ActiveForm::end(); &#63;>

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 run method will be called in the final end() method

public function run()

Copy after login

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&#63;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['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();
}

Copy after login

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 &#63; $value : new JsExpression($value);
      }
    }
    return $options;
}

Copy after login

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"
    });
});

Copy after login

4. Other methods: errorSummary, validate, validateMultiple

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

Copy after login

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)

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 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;
}

Copy after login

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>

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, [
      'model' => $model,
      'attribute' => $attribute,
      'form' => $this,
]));
}

Copy after login

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...
}

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:在每个属性在验证之后触发,格式为:

function ($form, attribute, messages) {
}

Copy after login

5、表单中的其它属性

$validateOnSubmit:提交表单的时候进行验证
$errorSummary:总的错误提示地方的样式
$attributes:这个属性比较特殊,它是在创建field的时候,在field中为这个form中的$attributes赋值的。这样可以确保通过field方法生成的输入表单都可以进行验证

更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles