search
HomeBackend DevelopmentPHP TutorialYii uses Forms, yiiforms_PHP tutorial

Yii uses Forms, yiiforms

1. Create model

 <p>a.加入基类</p> <p>     use yii/base/Model</p> <p>b.创建类继承自基类</p> <p>c.创建所需要的变量</p> <p>e.定义规则</p> <p>f.注意里面用[]括起来</p> <p>例如:</p> <pre class="code"><?<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>
<p>该类继承自Yii 提供的一个基类 [[yii\base\Model]],该基类通常用来表示数据</p>
<p>补充:[[yii\base\Model]] 被用于普通模型类的父类并与数据表<strong>无关</strong>。[[yii\db\ActiveRecord]] 通常是普通模型类的父类但与数据表有关联(译注:[[yii\db\ActiveRecord]] 类其实也是继承自 [[yii\base\Model]],增加了数据库处理)。</p>
<p><code>EntryForm</code> 类包含 <code>name</code> 和 <code>email</code> 两个公共成员,用来储存用户输入的数据。它还包含一个名为 <code>rules()</code> 的方法,用来返回数据验证规则的集合。上面声明的验证规则表示: 
<ul>
<li><code>name</code> 和 <code>email</code> 值都是必须的 
<li><code>email</code> 的值必须满足email规则验证</li></ul>
<p>如果你有一个处理用户提交数据的 <code>EntryForm</code> 对象,你可以调用它的 [[yii\base\Model::validate()|validate()]] 方法触发数据验证。如果有数据验证失败,将把 [[yii\base\Model::hasErrors|hasErrors]] 属性设为 ture,想要知道具体发生什么错误就调用 [[yii\base\Model::getErrors|getErrors]]。</p>
<pre class="code"><?<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

<p>下面你得在 <code>site</code> 控制器中创建一个 <code>entry</code> 操作用于新建的模型。操作的创建和使用已经在说一声你好小节中解释了。</p>
<pre class="code"><?<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 a 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.

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

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 email format is incorrect), the entry view will render the output, along with the form and the details of the validation error.

<p>注意:在这个简单例子里我们只是呈现了有效数据的确认页面。实践中你应该考虑使用 [[yii\web\Controller::refresh()|refresh()]] 或 [[yii\web\Controller::redirect()|redirect()]] 去避免表单重复提交问题。</p>
<p> </p>

3. Create a view

<p>最后创建两个视图文件 <code>entry-confirm</code> 和 <code>entry</code>。他们会被刚才创建的 <code>entry</code> 操作渲染。 
<p><code>entry-confirm</code> 视图简单地显示提交的 name 和 email 数据。视图文件保存在 <code>views/site/entry-confirm.php</code>。</p>
<pre class="code"><?<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>
<p><code>entry</code> 视图显示一个 HTML 表单。视图文件保存在 <code>views/site/entry.php</code></p>
<pre class="code"><?<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>(); ?>
<p>视图使用了一个功能强大的小部件 [[yii\widgets\ActiveForm|ActiveForm]] 去生成 HTML 表单。其中的 <code>begin()</code> 和 <code>end()</code> 分别用来渲染表单的开始和关闭标签。在这两个方法之间使用了 [[yii\widgets\ActiveForm::field()|field()]] 方法去创建输入框。第一个输入框用于 “name”,第二个输入框用于 “email”。之后使用 [[yii\helpers\Html::submitButton()]] 方法生成提交按钮。</p>
<pre class="code"><span>use</span><span> yii\helpers\Html;
</span><span>use</span> yii\wigets\ActiveForm;

Remember to use widgets, you need to introduce these two

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/924355.htmlTechArticleYii uses Forms, yiiforms 1. Create model a. Add base class use yii/base/Model b. Create class Inherited from the base class c. Create the required variables e. Define the rules f. Note that it is enclosed by []. For example:...
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

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

Video Face Swap

Video Face Swap

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

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment