多应用+插件架构,代码干净,支持一键云编译,码云点赞13K star,4.8-4.12 预售价格198元 广告
## 基础表单 **表单模型文件位置** > 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 ![](https://box.kancloud.cn/2015-11-22_56514c0d01dec.png) ![](https://box.kancloud.cn/2015-11-22_56514c0d39aae.png) ![](https://box.kancloud.cn/2015-11-22_56514c0d4adf8.png)