Yii uses Forms

WBOY
WBOYOriginal
2016-08-08 09:33:00792browse

1. Create a model

a. Add a base class

Use yii/base/Model

b. Create a class that inherits from the base class

c. Create the required variables

e. Define rules

f. Note that it is enclosed in []

For example:

<?<span>php

namespace app\models;

</span><span>use</span><span> yii\base\Model;

</span><span>class</span> EntryForm <span>extends</span><span> Model
{
    </span><span>public</span> <span>$name</span><span>;
    </span><span>public</span> <span>$email</span><span>;

    </span><span>public</span> <span>function</span><span> rules()
    {
        </span><span>return</span><span> [
            [[</span>'name', 'email'], 'required'],<span>
            [</span>'email', 'email'],<span>
        ];
    }
}</span>

This class inherits from a base class [[yiibaseModel]] provided by Yii, which is usually used to represent data

Added: [[yiibaseModel]] is used as the parent class of ordinary model classes and has nothing to do with data tables. [[yiidbActiveRecord]] is usually the parent class of a normal model class but is related to the data table (Translation: The [[yiidbActiveRecord]] class actually inherits from [[yiibaseModel]], adding database processing).

The

EntryForm class contains two public members: name and email, which are used to store user-entered data. It also contains a method called rules() that returns a collection of data validation rules. The validation rule declared above means:

    Both the
  • name and email values ​​are required The value of
  • email must meet the email rule verification

If you have an EntryForm object that handles user-submitted data, you can call its [[yiibaseModel::validate()|validate()]] method to trigger data validation. If data validation fails, the [[yiibaseModel::hasErrors|hasErrors]] attribute will be set to true. If you want to know what error occurred, call [[yiibaseModel::getErrors|getErrors]].

<?<span>php
</span><span>$model</span> = <span>new</span><span> EntryForm();
</span><span>$model</span>->name = 'Qiang'<span>;
</span><span>$model</span>->email = 'bad'<span>;
</span><span>if</span> (<span>$model</span>-><span>validate()) {
    </span><span>//</span><span> 验证成功!</span>
} <span>else</span><span> {
    </span><span>//</span><span> 失败!
    // 使用 $model->getErrors() 获取错误详情</span>
}

2. Create operation

Next you have to create an entry operation in the site controller for the new model. The creation and use of actions has been explained in the Say hello section.

<?<span>php

namespace app\controllers;

</span><span>use</span><span> Yii;
</span><span>use</span><span> yii\web\Controller;
</span><span>use</span><span> app\models\EntryForm;

</span><span>class</span> SiteController <span>extends</span><span> Controller
{
    </span><span>//</span><span> ...其它代码...</span>

    <span>public</span> <span>function</span><span> actionEntry()
    {
        </span><span>$model</span> = <span>new</span><span> EntryForm;

        </span><span>if</span> (<span>$model</span>->load(Yii::<span>$app</span>->request->post()) && <span>$model</span>-><span>validate()) {
            </span><span>//</span><span> 验证 $model 收到的数据

            // 做些有意义的事 ...</span>

            <span>return</span> <span>$this</span>->render('entry-confirm', ['model' => <span>$model</span><span>]);
        } </span><span>else</span><span> {
            </span><span>//</span><span> 无论是初始化显示还是数据验证错误</span>
            <span>return</span> <span>$this</span>->render('entry', ['model' => <span>$model</span><span>]);
        }
    }
}</span>

This operation first creates an EntryForm object. Then try to collect user-submitted data from $_POST, which is collected by Yii's [[yiiwebRequest::post()]] method. If the model is successfully populated with data (that is, the user has submitted the HTML form), the operation will call [[yiibaseModel::validate()|validate()]] to ensure that the user submitted valid data.

Added: The expression Yii::$app represents the application instance, which is a globally accessible singleton. At the same time, it is also a service locator, which can provide components with specific functions such as request, response, db and so on. In the above code, the request component is used to access the $_POST data received by the application instance.

After the user submits the form, the operation will render a view named entry-confirm to confirm the data entered by the user. If the form is submitted without filling it out, or the data contains errors (Translator: such as the email format is incorrect), the entry view will render the output, along with the form and the details of the validation error.

Note: In this simple example we only present the confirmation page with valid data. In practice, you should consider using [[yiiwebController::refresh()|refresh()]] or [[yiiwebController::redirect()|redirect()]] to avoid the problem of repeated form submission.

3. Create a view

Finally create two view files entry-confirm and entry. They will be rendered by the entry operation just created. The

entry-confirm view simply displays the submitted name and email data. View files are saved at views/site/entry-confirm.php.

<?<span>php
</span><span>use</span><span> yii\helpers\Html;
</span>?>
<p>You have entered the following information:</p>

<ul>
    <li><label>Name</label>: <?= Html::encode(<span>$model</span>->name) ?></li>
    <li><label>Email</label>: <?= Html::encode(<span>$model</span>->email) ?></li>
</ul>
The

entry view displays an HTML form. View files are saved in views/site/entry.php

<?<span>php
</span><span>use</span><span> yii\helpers\Html;
</span><span>use</span><span> yii\widgets\ActiveForm;
</span>?>
<?php <span>$form</span> = ActiveForm::begin(); ?>

    <?= <span>$form</span>->field(<span>$model</span>, 'name') ?>

    <?= <span>$form</span>->field(<span>$model</span>, 'email') ?>

    <div <span>class</span>="form-group">
        <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
    </div>

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

The view uses a powerful widget [[yiiwidgetsActiveForm|ActiveForm]] to generate HTML forms. Among them, begin() and end() are used to render the opening and closing tags of the form respectively. The [[yiiwidgetsActiveForm::field()|field()]] method is used between these two methods to create the input box. The first input box is for "name" and the second input box is for "email". Then use the [[yiihelpersHtml::submitButton()]] method to generate a submit button.

<span>use</span><span> yii\helpers\Html;
</span><span>use</span> yii\wigets\ActiveForm;

Remember to use widgets, you need to introduce these two

The above introduces the use of Forms in Yii, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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