1.创建model /biaodan.php
<?php
/**
* Created by PhpStorm.
* User: moka同学
* Date: 2016/08/05
* Time: 10:26
*/
namespace app\models; use Yii;
use yii\base\Model;
class Biaodan extends Model{
public $name;
public $pass;
public $email;
public $sex;
public $edu;
public $hobby;
public $info; //设置验证规则
public function rules()
{
return [
[['name','pass','email','sex','edu','hobby','info'],'required'],
['email','email','message'=>'这里是邮箱'],
['name','string','length'=>[2,10]]
];
} //定义表单标签
public function attributeLabels()
{
return [
'name'=>'名称',
'email'=>'邮箱',
'pass'=>'密码',
'edu'=>'教育',
'sex'=>'性别',
'hobby'=>'爱好',
'info'=>'简介'
];
}
}
?>
注:
自定义标签,用于显示表单标签
rules规则的创建,用于验证表单数据
2.控制器 BiaodanController.php
<?php
/**
* Created by PhpStorm.
* User: moka同学
* Date: 2016/08/05
* Time: 10:23
*/
namespace app\controllers; use app\models\Biaodan;
use yii\web\Controller; class BiaodanController extends Controller{
public $layout = "home";
public function actionIndex(){
// print_r($_POST);die();
$model = new Biaodan();
//如果有表单值就需要通过验证
if($model->load(\Yii::$app->request->post()) && $model->validate()){
return $this->render('index-two',['model'=>$model]);
}else{
return $this->render('index',['model'=>$model]);
}
}
}
?>
注:
\Yii::$app->request->post() 获取表单提交过来的数据 3.视图 index.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model,'name')->textInput(['style'=>'width:200px;'])?>
<?=$form->field($model,'pass')->passwordInput(['style'=>'width:200px;'])?>
<?=$form->field($model,'email')->textInput(['style'=>'width:200px;'])?>
<?=$form->field($model,'sex')->radioList(['1'=>'男','2'=>'女'])?>
<?=$form->field($model,'edu')->dropDownList(['1'=>'大学','2'=>'中学','3'=>'小学'],['style'=>'width:200px;'])?>
<?=$form->field($model,'hobby')->checkboxList(['篮球'=>'篮球','排球'=>'排球','乒乓球'=>'乒乓球'])?>
<?=$form->field($model,'info')->textarea(['rows'=>3,'style'=>'width:400px;'])?>
<div class="form-group">
<?=Html::submitButton('提交',['class'=>'btn btn-primary'])?>
</div>
<?php $form = ActiveForm::end(); ?>
注:
视图也可以使用gii去生成,但是还是需要更改很多地方
index-two.php (可以忽略)
<?php
use yii\helpers\Html;
?>
<ul>
<li><label><?=$model->name;?></label></li> <!--//原生写法-->
<li><label><?=Html::encode($model->pass)?></label></li> <!--//小部件写法-->
</ul>
注:
表单未完,还有很多bootstrap样式用于表单中
以上~~
注:~ 转载请注明出处。QQ1727728211