Home  >  Article  >  Yii2 framework usage tutorial: how to create a form

Yii2 framework usage tutorial: how to create a form

伊谢尔伦
伊谢尔伦Original
2017-07-04 11:35:102355browse

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(); ?>

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;]); ?>

The middle is The input box of each item ends with end

<?php ActiveForm::end(); ?>

2. Methods in the form

The begin() method in Widget 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([&#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);
}
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();
}
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;
}
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"
    });
});
4. Other methods: errorSummary, validate, validateMultiple

public function errorSummary($models, $options = [])
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)
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;
}


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>

$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,
]));
}

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

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

function ($form, attribute, messages) {
 ...return false to cancel the validation...
}

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

function ($form, attribute, messages) {
}

5、表单中的其它属性

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

相关课程推荐:

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

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

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

Statement:
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