首先创建model层
因为要使用表单小部件 所以要加载相应的组件
这里需要的组件有
yii\widgets\ActiveForm 和
yii\helpers\Html
接下来在model定义的class里 写方法
首先我们要定义需要使用表单小部件的name值
不多说上代码
<?phpnamespace 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 agegat(){ $agea=array(); for($i=1;$i<100;$i++){ $agea[$i]=$i; } return $agea;} static public function dataarr($data){ $arr = array(); foreach($data as $key=>$value){ $arr[$value['kid']] = $value['kname']; } return $arr; }}
在这个model里 有将英文表头转换中文的方法 attributuLabels 还有 我们处理单选多选还有下拉框值得方式 dataarr 接下来 我 们需要创建controller
<?phpnamespace frontend\controllers;use yii\web\Controller;use yii;use db;use frontend\models\Form;class FormController extends Controller{ public function actionIndex(){ $sql = 'select * from form'; $data = yii::$app->db->createCommand($sql)->queryAll(); $arr = Form::dataarr($data); $agea=Form::agegat(); //var_dump($arr);die; $model = new Form(); return $this->render('form',['model'=>$model,'data'=>$arr,'agea'=>$agea]); } public function actionAdd(){ $data = Yii::$app->request->post(); echo $name = $data['Form']['name']; }}
然后就是在我门的view层 展示出来
<?phpuse yii\helpers\Html;use yii\widgets\ActiveForm;$form = ActiveForm::begin(['id' => 'login-form','options' => ['class' => 'form-horizontal'],'action'=>'?r=form/add','method'=>'post',]) ?><?= $form->field($model, 'name') ?><?= $form->field($model, 'pwd')->passwordInput() ?><? $model->sex = '1'?><?= $form->field($model, 'sex')->radioList(['0'=>'男','1'=>'女'])?><? $model->hobby = ['swim','baseball' ] ?><?= $form->field($model, 'hobby')->checkboxList(['basketball'=>'篮球','baseball'=>'棒球','swim'=>'游泳']) ?><? $model->age = 3?> <?= $form->field($model, 'age')->dropDownList($agea) ?><div class="form-group"><div class="col-lg-offset-1 col-lg-11"><?= Html::submitButton('提交', ['class' => 'btn btn-primary']) ?></div></div><?php ActiveForm::end() ?>
好,到这里是不是感觉大功告成了。
恩,不用谢我。
来源:https://www.cnblogs.com/aini521521/p/6993618.html