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 [ [['name', 'email'], 'required'], ['email', 'email'], ]; } }
This class inherits from a base class yii\base\Model provided by Yii, which is usually used to represent data.
信息: yii\base\Model 被用于普通模型類的父類并與數(shù)據(jù)表無關(guān)。yii\db\ActiveRecord 通常是普通模型類的父類但與數(shù)據(jù)表有關(guān)聯(lián)(譯注:yii\db\ActiveRecord 類其實(shí)也是繼承自 yii\base\Model,增加了數(shù)據(jù)庫處理)。
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 = 'Qiang'; $model->email = 'bad'; if ($model->validate()) { // 驗(yàn)證成功! } else { // 失敗! // 使用 $model->getErrors() 獲取錯(cuò)誤詳情 }
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 { // ...現(xiàn)存的代碼... public function actionEntry() { $model = new EntryForm; if ($model->load(Yii::$app->request->post()) && $model->validate()) { // 驗(yàn)證 $model 收到的數(shù)據(jù) // 做些有意義的事 ... return $this->render('entry-confirm', ['model' => $model]); } else { // 無論是初始化顯示還是數(shù)據(jù)驗(yàn)證錯(cuò)誤 return $this->render('entry', ['model' => $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.
信息: 表達(dá)式 Yii::$app 代表應(yīng)用實(shí)例,它是一個(gè)全局可訪問的單例。 同時(shí)它也是一個(gè)服務(wù)定位器, 能提供 request,response,db 等等特定功能的組件。 在上面的代碼里就是使用 request 組件來訪問應(yīng)用實(shí)例收到的 $_POST 數(shù)據(jù)。
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, 'name') ?> <?= $form->field($model, 'email') ?> <div class="form-group"> <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?> </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.
After entering valid name and email information and submitting, you will see a confirmation page showing the data you submitted.
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

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

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

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

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

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

The steps to containerize and deploy Yii applications using Docker include: 1. Create a Dockerfile and define the image building process; 2. Use DockerCompose to launch Yii applications and MySQL database; 3. Optimize image size and performance. This involves not only specific technical operations, but also understanding the working principles and best practices of Dockerfile to ensure efficient and reliable deployment.

With the rapid development of the Internet, APIs have become an important way to exchange data between various applications. Therefore, it has become increasingly important to develop an API framework that is easy to maintain, efficient, and stable. When choosing an API framework, Yii2 and Symfony are two popular choices among developers. So, which one is more suitable for API development? This article will compare these two frameworks and give some conclusions. 1. Basic introduction Yii2 and Symfony are mature PHP frameworks with corresponding extensions that can be used to develop
