## 基礎表單
**表單模型文件位置**
> F:\wwwroot\Yii\basic\models\TestForm.php
**表單模型文件內容**
~~~
<?php
namespace app\models;
use yii\base\Model;
// 測試表單
class TestForm extends Model{
// 用戶賬號
public $username;
// 用戶密碼
public $password;
// 密保郵箱
public $email;
// 驗證規則
public function rules(){
return [
// 以下字段為必填項目
[["username", "password", "email"], "required"],
// 郵箱的驗證規則為email
["email", "email"]
];
}
}
~~~
**表單動作文件位置**
> F:\wwwroot\Yii\basic\controllers\SiteController.php
先引入表單模型文件
`use app\models\TestForm;`
**表單動作文件代碼**
~~~
// Form動作
public function actionForm(){
// 表單對象
$test = new TestForm();
// 表單屬性
$test->username = "iguoji";
$test->password = "123456";
$test->email = "asgeg@qq.com";
// 驗證屬性
if($test->validate()){
echo "正確的表單屬性!";
}else{
print_r($test->getErrors());
exit;
}
}
~~~
測試結果:http://127.0.0.1/index.php?r=site/form
## 實例表單
**修改表單動作文件**
~~~
// Form動作
public function actionForm(){
// 表單對象
$test = new TestForm();
/*// 表單屬性
$test->username = "iguoji";
$test->password = "123456";
$test->email = "asgeg@qq.com";
// 驗證屬性
if($test->validate()){
echo "正確的表單屬性!";
}else{
print_r($test->getErrors());
exit;
}*/
// 獲取用戶提交的信息,返回數組形式的數據
$postData = Yii::$app->request->post();
// 將數據填充到模型中,無需考慮字段如何對應,因為web頁面的字段是根據模型自動生成的,返回true或false
$loadRel = $test->load($postData);
// 驗證模型中填充的數據是否符合驗證規則
$valiRel = $test->validate();
// 如果提交沒問題,跳到form-confirm頁面
if($loadRel && $valiRel){
return $this->render("form-confirm", ["model" => $test]);
}else{
// 如果沒有提交信息,顯示表單頁面,并將模型對象賦予model變量提供給前臺調用
return $this->render("form", ["test" => $test]);
}
}
~~~
**創建視圖顯示頁面**
> F:\wwwroot\Yii\basic\views\site\form.php
~~~
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$this->title = "表單測試頁面!";
?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($test, "username")->label("用戶賬號");?>
<?= $form->field($test, "password")->label("用戶密碼");?>
<?= $form->field($test, "email")->label("密保郵箱");?>
<div class="form-group">
<?= Html::submitButton("提交信息", ["class" => "btn btn-primary"]);?>
</div>
<?php ActiveForm::end(); ?>
~~~
**從這里的代碼明顯的看出yii2和bootstrap有著深度的結合**
> F:\wwwroot\Yii\basic\views\site\form-confirm.php
~~~
<?php
use yii\helpers\Html;
?>
<p>表單信息提交結果</p>
<ul>
<li><label>用戶賬號</label>: <?= Html::encode($model->username);?></li>
<li><label>用戶密碼</label>: <?= Html::encode($model->password);?></li>
<li><label>密保郵箱</label>: <?= Html::encode($model->email);?></li>
</ul>
~~~
**表單頁面效果測試**
訪問頁面:http://127.0.0.1/index.php?r=site/form


