1. 程式人生 > >使用Yii2.0建立表單元件(input/單選按鈕組/textarea文字域/檔案上傳...)

使用Yii2.0建立表單元件(input/單選按鈕組/textarea文字域/檔案上傳...)

使用Yii2.0建立表單元件

在Yii中,通過使用yii\widgets\ActiveForm類的方式使用表單。

在View檢視中顯示的表單會有一個相對應的model模型,用來驗證其輸入的伺服器資料。因此首先定義模型,再建立基於模型的表單。

下面使用一個專案中的例項以展示表單的建立:

1.Model:該表單的模型:

class Projects extends ActiveRecord
{
    /**
     * 欄位驗證規則
     * @return array
     */
    public function rules()
    {
        return [
            ["type", "required", "message" => "{attribute}不可為空"],
            ["type", "in", "range" => ["vr", "train"], "message" => "{attribute}輸入有誤"],

            ["name", "filter", "filter" => "trim"],
            ["name", "required", "message" => "{attribute}不可為空"],
            ["name", "string", "length" => [3, 80], "message" => "{attribute}長度應在3~80個字元之間"],

            ["applicant_name", "filter", "filter" => "trim"],
            ["applicant_name", "required", "message" => "{attribute}不可為空"],
            ["applicant_name", "string", "length" => [2, 20], "message" => "{attribute}長度應在2~20個字元之間"],

            ["team", "filter", "filter" => "trim"],
            ["team", "required", "message" => "{attribute}不可為空"],
            ["team", "string", "length" => [2, 80], "message" => "{attribute}長度應在2~80個字元之間"],

            ["description", "required", "message" => "{attribute}不可為空"],
            ["description", "string", "min" => 10, "message" => "{attribute}長度應大於10個字元"],

            [["file"], "file", "extensions" => "gif, jpg, jpeg, png, pdf, doc, docx, ppt, pptx, xls, xlsx, zip, rar", "maxSize" => 1024 * 1024 * 10, "wrongExtension" => "僅支援上傳 {extensions} 型別的檔案", "tooBig" => "檔案 \"{file}\" 太大了。 請將檔案大小控制在 {formattedLimit} 以內!"]
        ];
    }
    //...
}

2.HTML:該表單的前端HTML佈局(靜態時):

<div class="edit_info part active" style="padding-top: 10px;">
    <h2>專案申報編輯</h2>
    <form>
        <div class="per_item nospace">
            <span>*專案名稱:</span>
            <label for=""><input type="text"></label>
        </div>
        <div class="per_item type">
            <span>*專案型別:</span>
            <label for="vr"><input type="radio" name="type" id="vr">VR應用</label>
            <label for="intelli"><input type="radio" name="type" id="intelli">人才培養</label>
        </div>
        <div class="per_item nospace">
            <span>*申 報 人 :</span>
            <label for=""><input type="text"></label>
        </div>
        <div class="per_item">
            <span>*專案團隊:</span>
            <label for=""><input type="text"><p>請填寫專案團隊人員姓名,姓名之間用“;”隔開</p></label>
        </div>
        <div class="per_item">
            <span>*專案概述:</span>
            <label for=""><textarea></textarea><p>請簡要說明專案立項的必要性、專案目標、實施方案、籌資方案、組織方式、相關基礎條件等</p></label>
        </div>
        <div class="per_item" style="margin-top: 80px;">
            <span>*上傳附件:</span>
            <label for="file">+ 上傳附件<input type="file" id="file"></label>
            <p>請上傳專案方案詳細的文件材料等,多個材料請打包成壓縮包上傳</p>
        </div>
        <div class="btn_group" style="text-align: center;">
            <button type="button" id="commit_btn">確認提交</button>
            <button type="button" id="save_btn">暫時儲存</button>
        </div>
    </form>
</div>

3.Controller:在控制器中,將傳遞一個模型的例項到檢視,ActiveForm小部件用以顯示錶單。以下例項將分別演示input、textarea、單選按鈕組、檔案上傳元件的使用:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(["id" => "form-new-edit"]); ?>
<!-- input -->
<?= $form->field($project,'name',[
        'options'   => [],
        'template'  => "<div class='per_item nospace'><span>*專案名稱:</span><label for=''>{input}{error}</label></div>"
    ])->textInput([
        'autofocus'     => true,
        'placeholder'   => ''
    ])
?>
<!-- 單選按鈕組radio -->
<div class="per_item type" style="position: relative;">
    <span>*專案型別:</span>
    <?= $form->field($project,"type")->radioList(
            ['0' =>  'VR應用', '1' =>  '人才培養'],
            [
                'item' => function($index,$label,$name,$checked,$value){
                    $checked = $index ? "" : "checked";
                    $return  = "<label for='t".$index."'>";
                    $return .= "<input type='radio' name='type' id='t".$index."'".$checked." value='".$label."'/>";
                    $return .= ucwords($label);
                    $return .= "</label>";
                    return $return;
                }
            ]
        )->label(false);
    ?>
</div>
<!-- textarea文字域 -->
<?= $form->field($project,"description",[
        'options'   => [],
        'template'  => "<div class='per_item'><span>*專案概述:</span><label for='' style='height: inherit;margin-bottom: 20px;'>{input}<p>請簡要說明專案立項的必要性、專案目標、實施方案、籌資方案、組織方式、相關基礎條件等</p>{error}</label></div>"
    ])->textarea([
        'autofocus'     => false,
        'placeholder'   => ''
    ])
?>
<!-- 檔案上傳按鈕file -->
<div class="per_item fileUploader">
    <span>*上傳附件:</span>
    <?= $form->field($project,"file")->fileInput() ?>
    <p>請上傳專案方案詳細的文件材料等,多個材料請打包成壓縮包上傳</p>
</div>
<!-- 提交按鈕button -->
<div class="btn_group" style="text-align: center;">
    <?= Html::submitButton('確認提交',["id" => "commit_btn", "type" => "button"]) ?>
    <?= Html::submitButton('暫時儲存',["id" => "save_btn", "type" => "button"]) ?>
</div>
<?php $form = ActiveForm::end(); ?>

4.View:檢視效果:


使用Yii2.0建立下拉選單參見另一篇博。