Yii uses Forms

Aug 08, 2016 am 09:33 AM
email entry gt model yii

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>
Copy after login

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>
}
Copy after login

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>
Copy after login

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

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;
Copy after login

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 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)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

How to use email, smtplib, poplib, imaplib modules to send and receive emails in Python How to use email, smtplib, poplib, imaplib modules to send and receive emails in Python May 16, 2023 pm 11:44 PM

The journey of an email is: MUA: MailUserAgent - Mail User Agent. (i.e. email software similar to Outlook) MTA: MailTransferAgent - Mail transfer agent, which is those email service providers, such as NetEase, Sina, etc. MDA: MailDeliveryAgent - Mail delivery agent. A server of the Email service provider sender->MUA->MTA->MTA->if

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

Trezor Cold Wallet: Model One and Model T Features and Usage Guide Trezor Cold Wallet: Model One and Model T Features and Usage Guide Jan 19, 2024 pm 04:12 PM

After problems occurred in many centralized exchanges, more and more cryptocurrency investors began to transfer assets to cold wallets to reduce the risks posed by centralized exchanges. This article will introduce Trezor, the world's earliest cold wallet provider. Since the first cold wallet was launched in 2014, it has been sold in many countries around the world. Trezor's products include Model One launched in 2014 and the advanced version Model T launched in 2018. The following will continue to introduce the differences between these two products and other cold wallets. What is Trezor cold wallet? In 2014, Trezor launched the first cold wallet ModelOne. In addition to common BTC, ETH, USDT and other currencies, the wallet also supports more than 1,000 other currencies.

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

Symfony vs Yii2: Which framework is better for developing large-scale web applications? Symfony vs Yii2: Which framework is better for developing large-scale web applications? Jun 19, 2023 am 10:57 AM

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

See all articles