Yii2中对于表单和字段的支持组件为ActiveForm和ActiveField,
- <?php $form = ActiveForm::begin([
- 'id' => 'login-form',
- 'options' => ['class' => 'form-horizontal'],
- 'fieldConfig' => [
- 'template' => "{label} <div class="col-lg-3">{input}</div> <div class="col-lg-8">{error}</div>",
- 'labelOptions' => ['class' => 'col-lg-1 control-label'],
- ],
- ]); ?>
- <?= $form->field($model, 'username') ?>
- <?= $form->field($model, 'password')->passwordInput() ?>
上述代码生成两个带默认标签名(如Username,Password)的表单输入框(input)。
如果想更改输入框的标签及其样式,有两个方式,一个是通过labelOptions参数:
- <?= $form->field($model, 'username',['labelOptions' => ['label' => 'Nick name','class' => 'your own class']]) ?>
还有一个更加面向对象的方法是:
- <?= $form->field($model, 'username')->textInput()->hint('Please enter your nick name instead of email')->label('Nick name') ?>