search
HomePHP FrameworkYIIHow to use forms in yii framework

How to use forms in yii framework

How to create a form page that allows users to submit data. The page will display a form containing a name input box and an email input box. After submitting these two parts of information, the page will display the information entered by the user. (Recommended learning: yii framework)

In order to achieve this goal, in addition to creating an operation and two views, you also need to create a model.

Through this tutorial, you will learn:

Create a model to represent the data entered by the user through the form

Declare rules to validate the input Data

Generate an HTML form in the view

Create model

The model class EntryForm represents the data requested from the user. The class is as follows and stored in models/EntryForm.php file.

<?php

namespace app\models;

use Yii;
use yii\base\Model;

class EntryForm extends Model
{
    public $name;
    public $email;

    public function rules()
    {
        return [
            [[&#39;name&#39;, &#39;email&#39;], &#39;required&#39;],
            [&#39;email&#39;, &#39;email&#39;],
        ];
    }
}

This class inherits from a base class yii\base\Model provided by Yii, which is usually used to represent data.

信息: yii\base\Model 被用于普通模型类的父类并与数据表无关。yii\db\ActiveRecord 通常是普通模型类的父类但与数据表有关联(译注:yii\db\ActiveRecord 类其实也是继承自 yii\base\Model,增加了数据库处理)。

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 rules declared above indicate:

name and email values ​​are both required

The value of email must satisfy the email rule verification

If you have a system that processes user-submitted data EntryForm object, you can call its validate() method to trigger data validation. If there is data validation failure, the hasErrors attribute will be set to true. If you want to know what error occurred, call getErrors.

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

Create action

Next you have to create an entry operation in the site controller for the new model.

<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\EntryForm;

class SiteController extends Controller
{
    // ...现存的代码...

    public function actionEntry()
    {
        $model = new EntryForm;

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

            // 做些有意义的事 ...

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

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

信息: 表达式 Yii::$app 代表应用实例,它是一个全局可访问的单例。 同时它也是一个服务定位器, 能提供 request,response,db 等等特定功能的组件。 在上面的代码里就是使用 request 组件来访问应用实例收到的 $_POST 数据。

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 out the form, or if the data contains errors (Translator: For example, 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 refresh() or redirect() to avoid the problem of repeated form submission.

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. The view file should be saved in views/site/entry-confirm.php.

<?php
use yii\helpers\Html;
?>
<p>You have entered the following information:</p>
<ul>
    <li><label>Name</label>: <?= Html::encode($model->name) ?></li>
    <li><label>Email</label>: <?= Html::encode($model->email) ?></li>
</ul>

The entry view displays an HTML form. View files should be saved in views/site/entry.php.

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, &#39;name&#39;) ?>
    <?= $form->field($model, &#39;email&#39;) ?>
    <div class="form-group">
        <?= Html::submitButton(&#39;Submit&#39;, [&#39;class&#39; => &#39;btn btn-primary&#39;]) ?>
    </div>
<?php ActiveForm::end(); ?>

Use your browser to access the following URL to see if it works:

http://hostname/index.php?r=site/entry

You will see a page containing a form with two input boxes. Each input box has a label in front of it indicating the type of data that should be entered. If you click the submit button without filling in anything, or fill in an email address with an incorrect format, you will see an error message displayed under the corresponding input box.

How to use forms in yii frameworkAfter entering valid name and email information and submitting, you will see a confirmation page showing the data you submitted.

How to use forms in yii framework

The above is the detailed content of How to use forms in yii framework. For more information, please follow other related articles on the PHP Chinese website!

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
Yii's Community: Support and ResourcesYii's Community: Support and ResourcesApr 16, 2025 am 12:04 AM

The Yii community provides rich support and resources. 1. Visit the official website and GitHub to get the documentation and code. 2. Use official forums and StackOverflow to solve technical problems. 3. Report bugs and make suggestions through GitHubIssues. 4. Use documents and tutorials to learn the Yii framework.

Yii: A Strong Framework for Web DevelopmentYii: A Strong Framework for Web DevelopmentApr 15, 2025 am 12:09 AM

Yii is a high-performance PHP framework designed for fast development and efficient code generation. Its core features include: MVC architecture: Yii adopts MVC architecture to help developers separate application logic and make the code easier to maintain and expand. Componentization and code generation: Through componentization and code generation, Yii reduces the repetitive work of developers and improves development efficiency. Performance Optimization: Yii uses latency loading and caching technologies to ensure efficient operation under high loads and provides powerful ORM capabilities to simplify database operations.

Yii: The Rapid Development FrameworkYii: The Rapid Development FrameworkApr 14, 2025 am 12:09 AM

Yii is a high-performance framework based on PHP, suitable for rapid development of web applications. 1) It adopts MVC architecture and component design to simplify the development process. 2) Yii provides rich functions, such as ActiveRecord, RESTfulAPI, etc., which supports high concurrency and expansion. 3) Using Gii tools can quickly generate CRUD code and improve development efficiency. 4) During debugging, you can check configuration files, use debugging tools and view logs. 5) Performance optimization suggestions include using cache, optimizing database queries and maintaining code readability.

The Current State of Yii: A Look at Its PopularityThe Current State of Yii: A Look at Its PopularityApr 13, 2025 am 12:19 AM

YiiremainspopularbutislessfavoredthanLaravel,withabout14kGitHubstars.ItexcelsinperformanceandActiveRecord,buthasasteeperlearningcurveandasmallerecosystem.It'sidealfordevelopersprioritizingefficiencyoveravastecosystem.

Yii: Key Features and Advantages ExplainedYii: Key Features and Advantages ExplainedApr 12, 2025 am 12:15 AM

Yii is a high-performance PHP framework that is unique in its componentized architecture, powerful ORM and excellent security. 1. The component-based architecture allows developers to flexibly assemble functions. 2. Powerful ORM simplifies data operation. 3. Built-in multiple security functions to ensure application security.

Yii's Architecture: MVC and MoreYii's Architecture: MVC and MoreApr 11, 2025 pm 02:41 PM

Yii framework adopts an MVC architecture and enhances its flexibility and scalability through components, modules, etc. 1) The MVC mode divides the application logic into model, view and controller. 2) Yii's MVC implementation uses action refinement request processing. 3) Yii supports modular development and improves code organization and management. 4) Use cache and database query optimization to improve performance.

Yii 2.0 Deep Dive: Performance Tuning & OptimizationYii 2.0 Deep Dive: Performance Tuning & OptimizationApr 10, 2025 am 09:43 AM

Strategies to improve Yii2.0 application performance include: 1. Database query optimization, using QueryBuilder and ActiveRecord to select specific fields and limit result sets; 2. Caching strategy, rational use of data, query and page cache; 3. Code-level optimization, reducing object creation and using efficient algorithms. Through these methods, the performance of Yii2.0 applications can be significantly improved.

Yii RESTful API Development: Best Practices & AuthenticationYii RESTful API Development: Best Practices & AuthenticationApr 09, 2025 am 12:13 AM

Developing a RESTful API in the Yii framework can be achieved through the following steps: Defining a controller: Use yii\rest\ActiveController to define a resource controller, such as UserController. Configure authentication: Ensure the security of the API by adding HTTPBearer authentication mechanism. Implement paging and sorting: Use yii\data\ActiveDataProvider to handle complex business logic. Error handling: Configure yii\web\ErrorHandler to customize error responses, such as handling when authentication fails. Performance optimization: Use Yii's caching mechanism to optimize frequently accessed resources and improve API performance.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool