Yii2下拉框實現

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   strong   

詳細介紹yii2下拉框的實現方法,以商品分類的下拉框為例:

第一種方法:使用Html的activeDropDownList(),該方法的優點是:可以自訂下拉框的樣式。具體實現如下:

1.控制器中,擷取視圖中所需的資料

    public function actionList(){
        $category_model=new Category();
        $category_info=$category_model->find()->all();
        return $this->renderPartial(‘list‘,[‘category_info‘=>$category_info,‘category_model‘=>$category_model]);
    }

2.視圖中,use yii\helpers\Html;

<?php $form = ActiveForm::begin([]);?>
    <?php echo Html::activeDropDownList($category_model,‘category_name‘,ArrayHelper::map($category_info,‘category_id‘,‘category_name‘),[‘style‘=>‘border:1px solid    gray;width:150px;‘])?>           
<?php ActiveForm::end(); ?>

3.這樣之後,表單的下拉框名稱是:Category Name,如果要改變這個值,在控制器對應的模型中使用attributeLabels()方法,具體如下:

 

  public function attributeLabels(){
        return array(
            ‘category_name‘=>‘分類‘,
        );
    }

第二種方法:使用ActiveForm的dropDownList(),優點是使用的yii自訂的樣式,也可以自訂樣式

1.控制器中擷取視圖中需要的資料

2.視圖中,use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;

<?php $form = ActiveForm::begin([]);?>
    <?php echo $form->field($category_model,‘category_name‘)->dropDownList(ArrayHelper::map($category_info,‘category_id‘,‘category_name‘),[‘style‘=>‘border:1px solid blue;width:150px;‘])?>           
<?php ActiveForm::end(); ?>

補充:該方法也可以自訂樣式:具體如上代碼

各參數說明:

ArrayHelper::map()------------產生k=>v的一維或多維陣列

$category_info----------------後台擷取的資料

category_id-------------------option的value值

category_name---------------select 的name值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.