Yii2 表单

2019-04-15 14:17发布

参考
http://www.yiiframework.com/doc-2.0/guide-input-forms.html

结构

render('index', [ 'model' => new Dynasty(), ]); } } 'login-form','options' => ['class' => 'class_name'],'action'=>'test/index','method'=>'get',]); ?> field($model, 'username') ?> field($model, 'password')->passwordInput() ?>

规则

密码 field($model, 'password')->passwordInput() ?> 标签与提示 field($model, 'username')->textInput()->hint('请输入你的用户名')->label('用户名') ?> field($model, 'username[]',['inputOptions'=>['value'=>'abc','class'=>'form-control']]) ?>//默认值 邮箱 field($model, 'username')->input('email') ?> 上传 field($model, 'username')->fileInput(['multiple'=>'multiple']) ?> 多选列表 field($model, 'username[]')->checkboxList(['a' => '多选a', 'b' => '多选b', 'c' => '多选c']) ?> 单个选择框 field($model, 'username')->checkbox([],false)->label('已审核') ?> ?> 下拉列表 field($model, 'username[]')->dropDownList(['a' => '多选a', 'b' => '多选b', 'c' => '多选c']) ?> field($model, 'username[]')->dropDownList(['a' => '多选a', 'b' => '多选b', 'c' => '多选c'], ['prompt' => '多选b']) ?> 隐藏框 field($model, 'username')->hiddenInput(['1']) ?> ListBox field($model, 'username[]')->listBox(['a' => '多选a', 'b' => '多选b', 'c' => '多选c']) ?> 单选列表 field($model, 'username[]')->radioList(['a' => '单选a', 'b' => '单选b', 'c' => '单选c']) ?> 多行文本 field($model, 'username')->textarea() ?> widget扩展 field($model, 'username')->widget(yiiwidgetsMaskedInput::className(), ['mask' => '9999/99/99',]); ?>

验证

'用户名不能为空.'], ['username', 'length', 'min'=>3, 'max'=>12], ['date','default','value'=>date('Y-m-d H:i:s')], ['verifyCode', 'captcha'],//验证码 ]; } } 为空检测 [['username', 'password'], 'required', 'message'=>'不能为空'], 邮箱检测 ['username', 'email'], field($model, 'body')->textArea(['rows' => 6]) ?> field($model, 'verifyCode')->widget(Captcha::className(), [     'template' => '
{image}
{input}
', ]) ?>
    'btn btn-primary', 'name' => 'contact-button']) ?>

接收数据

public function actionIndex() { $model = new Dynasty(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { echo $model->username; return $this->render('index', ['model' => $model]); }else{ } }

上传


CONTROLLER
request->isPost) { $model = new Dynasty(); $model->file = UploadedFile::getInstance($model, 'file'); if ($model->file && $model->validate()) { $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension); //uploads 相对网站根目录 } return $this->render('index', ['model' => $model]); }

MODEL
'gif, jpg, png'], ]; } }

VIEW
'login-form','options' => ['enctype' => 'multipart/form-data']]); ?> field($model, 'username') ?> field($model, 'file')->fileInput() ?> field($model, 'password')->passwordInput() ?>