Home headlines Yii2 framework usage tutorial: how to create a form

Yii2 framework usage tutorial: how to create a form

Jul 04, 2017 am 11:35 AM
yii2 how Tutorial

Friends who are new to php. Everyone will want to find a framework that can be used quickly to learn to do projects. Generally speaking, I will choose ThinkPHP to try. This framework is not difficult to get started and can quickly develop an application. Suitable for small business applications. Because it was developed by Chinese people, Chinese support is better. There are relatively comprehensive documents, and the official website community is also relatively active. But at a certain stage, you are basically not satisfied with using ThinkPHP, and choose a high-performance development framework. Yii comes with a rich set of features, including MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access control, scaffolding, testing, etc., which can significantly shorten development time. Here our PHP Chinese website will take you to learn how to create forms using the yii2 framework from scratch. First of all, you can go to our php Chinese website to watch online

Yii2 Chinese Manual

You can also go to

##php Chinese website download siteDownload: Yii2 Chinese Manual

Let’s get to the point of creating the form in the yii2 framework:

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

Form form

Itself attributes
Attributes related to each item (field) input box in the form $fieldConfig About the attributes of validation
About the attributes of each field container style
Ajax validation
Front-end js event
Other attributes in the form

Let’s take a look at Yii first It contains the simplest login form and the generated html code and interface. Let’s have an intuitive understanding first.

<?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() ?>
  <p 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;]) ?>
  </p>
  <p class="form-group">
     <?= Html::submitButton(&#39;Login&#39;, [&#39;class&#39; => &#39;btn btn-primary&#39;, &#39;name&#39; => &#39;login-button&#39;]) ?>
  </p>
<?php ActiveForm::end(); ?>
Copy after login

The following is the generated form Html. 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 of each item ends with end

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

2. Methods in the form

The begin() method in Widget 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([&#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
The following is the generated Form verification

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 messages

in the model into one p middle.

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 will not be mentioned here.

3. Parameters in the form

1. Properties of the form itself

$action: Set the current form submission The url address, if it is empty, it is the current url$method: Submit method, post or get, the default is post

$option: This sets other attributes of the form, such as id, etc., if not set id will automatically generate an automatically increased id prefixed by $autoIdPrefix

//这个方法在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:

① The outermost p is the container of each field,

② label is the text description of each field,

③ input is the input element ,

④ There is also a p for error message.

<p 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]">
    <p class="help-block">Username cannot be blank.</p>
</p>
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:是否在客户端验证,也即是否生成前端js验证脚本(如果在form中设置了ajax验证,也会生成这个js脚本)。
② $enableAjaxValidation:是否是ajax验证
③ $validateOnChange:在输入框失去焦点并且值改变的时候验证
④ $validateOnType:正在输入的时候就进行验证
⑤ $validationDelay:验证延迟的时间,单位为毫秒

这5个属性都可以在创建每个field的时候单独设置,因为在field类中就有这5个属性。

关于每个field容器样式的属性:

$requiredCssClass:必填项的样式,默认为‘required'
$errorCssClass:验证错误的样式,默认值为‘has-error'
$successCssClass:验证正确的样式,默认值为‘has-success'
$validatingCssClass:验证过程中的样式,默认值为‘validating'

3、ajax验证

$validationUrl:ajax验证的url地方
$ajaxParam:url中的get参数,用来标明当前是ajax请求,默认值为‘ajax'
$ajaxDataType:ajax请求返回的数据格式

4、前端js事件属性

$beforeSubmit:在提交表单之前事件,如果返回false,则不会提交表单,格式为:

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

$beforeValidate:在每个属性在验证之前触发,格式为:

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方法生成的输入表单都可以进行验证

相关课程推荐:

1. 视频课程: 传智播客Yii开发大型商城项目视频教程

2. 视频课程: Yii2.0框架开发实战视频教程

3. 视频课程: Yii2框架搭建完整博客系统

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)

Tutorial on how to use Dewu Tutorial on how to use Dewu Mar 21, 2024 pm 01:40 PM

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

Quark browser usage tutorial Quark browser usage tutorial Feb 24, 2024 pm 04:10 PM

Quark Browser is a very popular multi-functional browser at the moment, but most friends don’t know how to use the functions in Quark Browser. The most commonly used functions and techniques will be sorted out below. Next, the editor will guide users. Here is a summary of the multi-functional usage tutorials of Quark Browser. Interested users can come and take a look together! Tutorial on how to use Quark Browser [2024-01-09]: How to scan test papers to see answers on Quark [2024-01-09]: How to enable adult mode on Quark Browser [2024-01-09]: How to delete used space on Quark [2024 -01-09]: How to clean up the Quark network disk storage space [2024-01-09]: How to cancel the backup of Quark [2024-01-09]: Quark

Upgrading numpy versions: a detailed and easy-to-follow guide Upgrading numpy versions: a detailed and easy-to-follow guide Feb 25, 2024 pm 11:39 PM

How to upgrade numpy version: Easy-to-follow tutorial, requires concrete code examples Introduction: NumPy is an important Python library used for scientific computing. It provides a powerful multidimensional array object and a series of related functions that can be used to perform efficient numerical operations. As new versions are released, newer features and bug fixes are constantly available to us. This article will describe how to upgrade your installed NumPy library to get the latest features and resolve known issues. Step 1: Check the current NumPy version at the beginning

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

Tutorial on how to turn off the payment sound on WeChat Tutorial on how to turn off the payment sound on WeChat Mar 26, 2024 am 08:30 AM

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

DisplayX (monitor testing software) tutorial DisplayX (monitor testing software) tutorial Mar 04, 2024 pm 04:00 PM

Testing a monitor when buying it is an essential part to avoid buying a damaged one. Today I will teach you how to use software to test the monitor. Method step 1. First, search and download the DisplayX software on this website, install it and open it, and you will see many detection methods provided to users. 2. The user clicks on the regular complete test. The first step is to test the brightness of the display. The user adjusts the display so that the boxes can be seen clearly. 3. Then click the mouse to enter the next link. If the monitor can distinguish each black and white area, it means the monitor is still good. 4. Click the left mouse button again, and you will see the grayscale test of the monitor. The smoother the color transition, the better the monitor. 5. In addition, in the displayx software we

What software is photoshopcs5? -photoshopcs5 usage tutorial What software is photoshopcs5? -photoshopcs5 usage tutorial Mar 19, 2024 am 09:04 AM

PhotoshopCS is the abbreviation of Photoshop Creative Suite. It is a software produced by Adobe and is widely used in graphic design and image processing. As a novice learning PS, let me explain to you today what software photoshopcs5 is and how to use photoshopcs5. 1. What software is photoshop cs5? Adobe Photoshop CS5 Extended is ideal for professionals in film, video and multimedia fields, graphic and web designers who use 3D and animation, and professionals in engineering and scientific fields. Render a 3D image and merge it into a 2D composite image. Edit videos easily

Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Mar 22, 2024 pm 12:21 PM

With the continuous development of smart phones, the functions of mobile phones have become more and more powerful, among which the function of taking long pictures has become one of the important functions used by many users in daily life. Long screenshots can help users save a long web page, conversation record or picture at one time for easy viewing and sharing. Among many mobile phone brands, Huawei mobile phones are also one of the brands highly respected by users, and their function of cropping long pictures is also highly praised. This article will introduce you to the correct method of taking long pictures on Huawei mobile phones, as well as some expert tips to help you make better use of Huawei mobile phones.