Yii2 yii\widgets\ActiveForm 配合 yii\helpers\Html 能生成帶客戶端/服務端雙重驗證的標準化表單。本文匯總所有常用輸入類型的調用代碼,可直接複製到 View 中使用。
<?php $form = ActiveForm::begin([
'action' => ['test/getpost'],
'method' => 'post',
'options' => ['class' => 'form-horizontal'], // Bootstrap 標準類
]); ?>
<?= Html::submitButton('提交', ['class' => 'btn btn-primary', 'name' => 'submit-button']) ?>
<?= Html::resetButton('重置', ['class' => 'btn btn-default', 'name' => 'reset-button']) ?>
<?php ActiveForm::end(); ?>
| 類型 | 方法調用 | 關鍵選項 |
|---|---|---|
| 文本框 | $form->field($model, 'username')->textInput(['maxlength' => 20]) | maxlength, placeholder, readonly, disabled |
| 密碼框 | $form->field($model, 'password')->passwordInput(['maxlength' => 20]) | 同文本框 |
| 單選框(組) | $form->field($model, 'sex')->radioList(['1'=>'男','0'=>'女']) | item 函數自定義標籤結構 |
| 單選框(單個) | $form->field($model, 'agree')->radio(['value'=>1, 'uncheck'=>null]) | uncheck 取消選中時的值 |
| 復選框(組) | $form->field($model, 'hobby')->checkboxList(['0'=>'籃球','1'=>'足球','2'=>'羽毛球']) | 多值存陣列/JSON |
| 復選框(單個) | $form->field($model, 'accept')->checkbox(['value'=>1, 'uncheck'=>0, 'label'=>'我同意']) | label 參數直接輸出文字 |
| 下拉框 | $form->field($model, 'edu')->dropDownList(['1'=>'大學','2'=>'高中','3'=>'初中'], ['prompt'=>'請選擇','style'=>'width:120px']) | prompt, options 分組 |
| 隱藏域 | $form->field($model, 'userid')->hiddenInput(['value' => 3]) | 不渲染 label、錯誤提示 |
| 文本域 | $form->field($model, 'info')->textarea(['rows' => 3]) | rows, cols, maxlength |
| 文件上傳 | $form->field($model, 'file')->fileInput() | 配合模型 ['file','file','extensions'=>'png,jpg'] |
| 靜態文本 | $form->field($model, 'name')->label(false)->textInput(['readonly'=>true]) | 或直接 Html::tag('p', $model->name) |
'template' => "{label}\n{input}\n{hint}\n{error}"(預設 label-input-error-hint)$form->field($model, 'attr', ['options'=>['class'=>'form-group col-md-6']]) 控制響應式佈局rules() 定義規則,ActiveForm 自動生成 JS 驗證(需引入 yii.activeForm.js)'enableAjaxValidation' => true,控制器 if (Yii::$app->request->isAjax && $model->load(...)) Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model);'beforeSubmit' => 'function(form) { console.log("提交前"); return true; }'ActiveForm 預設輸出 Bootstrap 3 結構。若用 BS4/5,需覆寫 fieldConfig:
'fieldConfig' => [
'template' => "{label}\n{input}\n{error}",
'labelOptions' => ['class' => 'col-sm-3 control-label'],
'inputOptions' => ['class' => 'form-control'],
'errorOptions' => ['class' => 'text-danger'],
],
收藏此表,構建表單頁不再查文檔,專注業務字段與驗證規則設計。