第一步、接着教程(1),我们在controllers/ZhyoulunController.php中添加两处,
1)
use app\models\EntryForm;
和
2)
public function actionEntry()
{
$model = new EntryForm;
if ($model->load(Yii::$app->request->post()) && $model->validate())
{
// 验证 $model 收到的数据
// 做些有意义的事 ...
return $this->render('entry-confirm', ['model' => $model]);
}
else
{
// 无论是初始化显示还是数据验证错误
return $this->render('entry', ['model' => $model]);
}
}<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
//注意这一行,和models/entryform.php对应
use app\models\EntryForm;
//类名ZhyoulunController必须和文件名对应
class ZhyoulunController extends Controller
{
public function actionHelloworld()
{
return $this->renderPartial('helloworld');
//return $this->render('helloworld');
}
/*
该操作首先创建了一个 EntryForm 对象。
然后尝试从 $_POST 搜集用户提交的数据,
并确保用户提交的是有效数据。
*/
public function actionEntry()
{
$model = new EntryForm;
if ($model->load(Yii::$app->request->post()) && $model->validate())
{
// 验证 $model 收到的数据
// 做些有意义的事 ...
return $this->render('entry-confirm', ['model' => $model]);
}
else
{
// 无论是初始化显示还是数据验证错误
return $this->render('entry', ['model' => $model]);
}
}
}第二步、在models文件夹中新建EntryForm.php
<?php
namespace app\models;
use yii\base\Model;
class EntryForm extends Model
{
public $name;
public $email;
public function rules()
{
//name 和 email 值都是必须的
//mail 的值必须满足 email 地址验证
return [
[['name', 'email'], 'required'],
['email', 'email'],
];
}
}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(); ?>entry-confirm.php
<?php
use yii\helpers\Html;
?>
<p>你输入的信息如下所示:</p>
<ul>
<li><label>Name</label>: <?= Html::encode($model->name) ?></li>
<li><label>Email</label>: <?= Html::encode($model->email) ?></li>
</ul>
输入信息
提交
参考:http://www.yiichina.com/guide/2/start-forms
转载请注明出处:http://blog.csdn.net/zhyoulun/article/details/40454181
原文地址:http://blog.csdn.net/zhyoulun/article/details/40454181