[moka同学笔记]yii2.0表单的使用

1.创建BiaodanController.php

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: moka同学
 5  * Date: 2016/08/05
 6  * Time: 10:23
 7  */
 8 namespace app\controllers;
 9 
10 use app\models\Biaodan;
11 use yii\web\Controller;
12 
13 class BiaodanController extends Controller{
14     public function actionIndex(){
15         print_r($_POST);die();
16         $model = new Biaodan();
17         //如果有表单值就需要通过验证
18         if($model->load(\Yii::$app->request->post()) && $model->validate()){
19             return $this->render('index-two',['model'=>$model]);
20         }else{
21             return $this->render('index',['model'=>$model]);
22         }
23     }
24 }
25 ?>

2.创建model,biaodan.php

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: moka同学
 5  * Date: 2016/08/05
 6  * Time: 10:26
 7  */
 8 namespace app\models;
 9 
10 use Yii;
11 use yii\base\Model;
12 class Biaodan extends Model{
13     public $name;
14     public $pass;
15     public $email;
16     public $sex;
17     public $edu;
18     public $hobby;
19     public $info;
20 
21     public function rules()
22     {
23         return [
24             [['name','pass','email','sex','edu','hobby','info'],'required'],
25             ['email','email','message'=>'这里是邮箱'],
26             ['name','string','length'=>[2,10]]
27         ];
28     }
29 
30     public function attributeLabels()
31     {
32         return [
33             'name'=>'名称',
34             'email'=>'邮箱',
35             'pass'=>'密码',
36             'edu'=>'教育',
37             'sex'=>'性别',
38             'hobby'=>'爱好',
39             'info'=>'简介'
40         ];
41     }
42 }
43 ?>

3.视图文件view/index.php

 1 <?php
 2 use yii\helpers\Html;
 3 use yii\widgets\ActiveForm;
 4 
 5 ?>
 6 <?php $form = ActiveForm::begin(); ?>
 7 <?=$form->field($model,'name')->textInput(['style'=>'width:200px;'])?>
 8 <?=$form->field($model,'pass')->passwordInput(['style'=>'width:200px;'])?>
 9 <?=$form->field($model,'email')->textInput(['style'=>'width:200px;'])?>
10 <?=$form->field($model,'sex')->radioList(['1'=>'男','2'=>'女'])?>
11 <?=$form->field($model,'edu')->dropDownList(['1'=>'大学','2'=>'中学','3'=>'小学'],['style'=>'width:200px;'])?>
12 <?=$form->field($model,'hobby')->checkboxList(['篮球'=>'篮球','排球'=>'排球','乒乓球'=>'乒乓球'])?>
13 <?=$form->field($model,'info')->textarea(['rows'=>3,'style'=>'width:400px;'])?>
14 <div class="form-group">
15     <?=Html::submitButton('提交',['class'=>'btn btn-primary'])?>
16 </div>
17 <?php $form = ActiveForm::end(); ?>

index-two.php

1 <?php
2 use yii\helpers\Html;
3 ?>
4 <ul>
5     <li><label><?=$model->name;?></label></li>   <!--//原生写法-->
6     <li><label><?=Html::encode($model->pass)?></label></li> <!--//小部件写法-->
7 </ul>

 

posted @ 2016-08-05 11:30  mokal同学  阅读(200)  评论(0编辑  收藏  举报