首先创建model层
因为要使用表单小部件 所以要加载相应的组件
这里需要的组件有
yii\widgets\ActiveForm 和
yii\helpers\Html
接下来在model定义的class里 写方法
首先我们要定义需要使用表单小部件的name值
不多说上代码
<?php
/**
* Created by PhpStorm.
* User: jinlei
* Date: 2017/5/10
* Time: 9:35
*/
namespace frontend\models;
use yii\base\Model;
use yii\widgets\ActiveForm;
use yii\helpers\Html;
class Form extends Model
{
public $name;
public $pwd;
public $sex;
public $hobby;
public $age;
public function rules(){
return[
];
}
public function attributeLabels(){
return[
'name'=>'用户名',
'pwd'=>'密码',
'sex'=>'性别',
'hobby'=>'爱好',
'age'=>'年龄'
];
}
static public function dataarr($data){
$arr = array();
foreach($data as $key=>$value){
$arr[$value['kid']] = $value['kname'];
}
return $arr;
}
}
在这个model里 有将英文表头转换中文的方法 attributuLabels
还有 我们处理单选多选还有下拉框值得方式 dataarr
接下来 我 们需要创建controller
<?php
/**
* Created by PhpStorm.
* User: jinlei
* Date: 2017/5/10
* Time: 9:39
*/
namespace frontend\controllers;
use yii\web\Controller;
use yii;
use db;
use frontend\models\Form;
class LoginController extends Controller
{
public function actionIndex(){
$sql = 'select kid,kname from exam_tiku';
$data = yii::$app->db->createCommand($sql)->queryAll();
$arr = Form::dataarr($data);
//var_dump($arr);die;
$model = new Form();
return $this->render('index',['model'=>$model,'data'=>$arr]);
}
public function actionAdd(){
$data = Yii::$app->request->post();
echo $name = $data['Form']['name'];
}
}
然后就是在我门的view层 展示出来
<?php
/**
* Created by PhpStorm.
* User: jinlei
* Date: 2017/5/10
* Time: 9:41
*/
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
'id' => 'login-form',
'options' => ['class' => 'form-horizontal'],
'action'=>'?r=login/add',
'method'=>'post',
]) ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'pwd')->passwordInput() ?>
<?= $form->field($model, 'sex')->radioList(['0'=>'男','1'=>'女']) ?>
<?= $form->field($model, 'hobby')->checkboxList(['basketball'=>'篮球','baseball'=>'棒球','swim'=>'游泳']) ?>
<?= $form->field($model, 'age')->dropDownList($data) ?>
<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end() ?>
在这个页面中 我们展示了 文本框 密码框 单选多选下拉框 其中下拉框的数据是从db中读取的