首页 > PHP教程 > php开发知识文章

php -- yii2框架中表单小部件的使用

本文主要介绍的是关于yii 2.0中表单小部件使用的相关内容,分享出来供大家参考学习,下面来看看详细的介绍:

首先创建model层,要加载相应的组件,这里需要的组件有yii/widgets/ActiveForm yii/helpers/Html

接下来在model定义的class里 写方法,首先我们要定义需要使用表单小部件的name值

model代码

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代码

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);
$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层 代码 

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中读取的

以上就是这篇文章php -- yii2框架中表单小部件的使用的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对本站的支持。

PHP Yii框架介绍

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。