Yii2 的 yii\widgets\ActiveForm 是構建表單的核心組件,支援客戶端/服務端驗證、AJAX 提交、字段自動生成等功能。本文提供完整使用範例與所有字段類型速查表。
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
/* @var $model app\models\ContactForm */
/* @var $form ActiveForm */
?>
<?php $form = ActiveForm::begin([
'id' => 'contact-form',
'action' => ['site/contact'],
'method' => 'post',
'options' => ['class' => 'form-horizontal', 'enctype' => 'multipart/form-data'],
'enableClientValidation' => true,
'enableAjaxValidation' => false,
'validateOnBlur' => true,
'validateOnChange' => false,
'validateOnSubmit' => true,
]); ?>
<!-- 字段將在這裡渲染 -->
<div class="form-group">
<?= Html::submitButton('提交', ['class' => 'btn btn-primary', 'name' => 'submit-btn']) ?>
<?= Html::resetButton('重置', ['class' => 'btn btn-outline-secondary']) ?>
</div>
<?php ActiveForm::end(); ?>
| 字段類型 | 方法 | 常用選項 | 輸出 HTML 示例 |
|---|---|---|---|
| 文本框 | textInput() | ['maxlength'=>50, 'placeholder'=>''] | <input type="text" ...> |
| 密碼框 | passwordInput() | ['maxlength'=>20] | <input type="password" ...> |
| 隱藏域 | hiddenInput() | ['value'=>$val] | <input type="hidden" ...> |
| 文本域 | textarea() | ['rows'=>6, 'cols'=>50] | <textarea ...> |
| 文件上傳 | fileInput() | ['accept'=>'image/*'] | <input type="file" ...> |
| 單選框 | radio() | ['label'=>'選項', 'value'=>1] | <input type="radio" ...> |
| 單選組 | radioList() | [1=>'男', 0=>'女'], ['item'=>fn()] | 多個 radio |
| 複選框 | checkbox() | ['value'=>1, 'uncheck'=>0] | <input type="checkbox" ...> |
| 複選組 | checkboxList() | [1=>A, 2=>B], ['separator'=>'<br>'] | 多個 checkbox |
| 下拉框 | dropDownList() | ['prompt'=>'請選擇', 'items'=>[]] | <select><option>... |
| 列表框 | listBox() | ['multiple'=>true, 'size'=>5] | <select multiple> |
| 提交按鈕 | Html::submitButton() | ['class'=>'btn btn-primary'] | <button type="submit"> |
| 重置按鈕 | Html::resetButton() | ['class'=>'btn btn-secondary'] | <button type="reset"> |
<?= $form->field($model, 'username')->textInput(['maxlength' => 20, 'autofocus' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => 20]) ?>
<?= $form->field($model, 'sex')->radioList(
['1' => '男', '0' => '女'],
['item' => function($index, $label, $name, $checked, $value) {
return "<label class='radio-inline'><input type='radio' name='$name' value='$value' " . ($checked ? 'checked' : '') . "> $label</label>";
}]
) ?>
<?= $form->field($model, 'education')->dropDownList(
['1' => '大學', '2' => '高中', '3' => '初中'],
['prompt' => '請選擇學歷', 'class' => 'form-control', 'style' => 'width: 200px;']
) ?>
<?= $form->field($model, 'hobbies')->checkboxList(
['basketball' => '籃球', 'football' => '足球', 'badminton' => '羽毛球'],
['item' => function($index, $label, $name, $checked, $value) {
return "<label class='checkbox-inline'><input type='checkbox' name='$name[]' value='$value' " . ($checked ? 'checked' : '') . "> $label</label>";
}]
) ?>
<?= $form->field($model, 'bio')->textarea(['rows' => 4, 'placeholder' => '自我介紹...']) ?>
<?= $form->field($model, 'avatar')->fileInput(['accept' => 'image/*']) ?>
<?= $form->field($model, 'user_id')->hiddenInput(['value' => Yii::$app->user->id]) ?>
<?= $form->field($model, 'email', [
'template' => "<div class='input-group'>{label}<span class='input-group-addon'>@</span>{input}{hint}{error}</div>",
'labelOptions' => ['class' => 'sr-only'],
'inputOptions' => ['class' => 'form-control', 'placeholder' => 'Email'],
'hintOptions' => ['class' => 'help-block', 'tag' => 'small'],
'errorOptions' => ['class' => 'help-block text-danger', 'tag' => 'div'],
])->textInput() ?>
<?php $form = ActiveForm::begin([
'id' => 'register-form',
'enableAjaxValidation' => true,
'validationUrl' => ['site/validate'], // 可選:自定義驗證端點
]); ?>
// 控制器
public function actionValidate() {
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
_csrf 隱藏域,無需手動添加'enctype' => 'multipart/form-data' 在 ActiveForm::begin()$form->field() 自動生成 <label for="id">,確保無障礙errorOptions 統一錯誤提示樣式rules() 中聲明 safe 驗證器允許大量賦值// 配置全局模板 (config/main.php)
'components' => [
'assetManager' => [
'bundles' => [
'yii\bootstrap4\BootstrapAsset' => ['css' => []], // 使用自定義 CSS
],
],
],
// 字段模板適配 Bootstrap 5
'template' => "<div class='mb-3'>{label}{input}{hint}{error}</div>",
'labelOptions' => ['class' => 'form-label'],
'inputOptions' => ['class' => 'form-control'],
'errorOptions' => ['class' => 'invalid-feedback', 'tag' => 'div'],
'hintOptions' => ['class' => 'form-text', 'tag' => 'small']
掌握 ActiveForm 核心 API 與字段類型,能快速構建功能完善、樣式統一、驗證健全的表單系統。