首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Yii2 ActiveForm 表單組件完整使用指南與字段類型速查表

     編輯:PHP 相關知識

Yii2 ActiveForm 表單組件完整使用指南與字段類型速查表

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() ?>

五、AJAX 驗證配置

<?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);
    }
}

六、常見問題與最佳實踐

  1. CSRF 防護:ActiveForm 自動包含 _csrf 隱藏域,無需手動添加
  2. 文件上傳:必須設置 'enctype' => 'multipart/form-data' 在 ActiveForm::begin()
  3. 標籤關聯:$form->field() 自動生成 <label for="id">,確保無障礙
  4. 錯誤樣式:配置 errorOptions 統一錯誤提示樣式
  5. 條件顯示:結合 JS 控制字段顯示/隱藏,而非後端不渲染
  6. 批量賦值:模型 rules() 中聲明 safe 驗證器允許大量賦值

七、Bootstrap 4/5 整合提示

// 配置全局模板 (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 與字段類型,能快速構建功能完善、樣式統一、驗證健全的表單系統。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved