首頁  >  問答  >  主體

自訂下拉式選單中的項目在Yii 2中無法正常運作

<p>我正在Yii 2中建立自己的下拉清單函數。我建立了一個函數和一個視圖,在視圖中,我的下拉表單中有多個項目。 </p> <pre class="brush:php;toolbar:false;"><?= $form->customDropDown($dpForm, 'color', [ 'items' => [ 'label' => 'red', 'value' => 'red', 'options' => [ 'style' => 'color: red' ] ] [ 'label' => 'blue', 'value' => 'blue', 'options' => [ 'style' => 'color: blue' ] ] ] </pre> <p>我創建的函數如下(它使用並位於ActiveForm中):</p> <pre class="brush:php;toolbar:false;"> public function customDropdown($model, $attribute, $items = [], $options = []) { $value = Html::getAttributeValue($model, $attribute); $field = $this->field($model, $attribute, $options); return $this->staticOnly ? $field : $field->dropDownList($items); } </pre> <p>問題是,當我打開我的下拉清單時,所有的東西都是一個選項或一個選項組,而不僅僅是帶有標籤和样式的選項。 </p> <p>在<em>Inspector</em>中的顯示效果如下:</p> <pre class="brush:html;toolbar:false;"><optgroup label='0'> <option value="label">red</option> <option value="value">red</option> </optgroup> <optgroup label="options"> <option value="style">color: red</option> </optgroup> </pre> <p>以此類推。我想要的效果如下:</p> <pre class="brush:html;toolbar:false;"><option value="red" style="color: red">red</option> </pre> <p>但是我似乎無法達到這個效果。 </p>
P粉268284930P粉268284930382 天前501

全部回覆(1)我來回復

  • P粉801904089

    P粉8019040892023-09-06 14:29:43

    為了實現所需的輸出,其中下拉清單中的每個項目都由一個具有指定標籤、值和樣式的單一<option>標籤表示,您需要按照以下方式修改您的程式碼: 在您的視圖檔案中,更新customDropDown函數呼叫以正確傳遞items陣列:

    <?= $form->customDropDown($dpForm, 'color', [
            [
                'label' => 'red',
                'value' => 'red',
                'options' => [
                    'style' => 'color: red'
                ]
            ],
            [
                'label' => 'blue',
                'value' => 'blue',
                'options' => [
                    'style' => 'color: blue'
                ]
            ],
        ]
    ); ?>
    更新的方法:
    public function customDropdown($model, $attribute, $items = [], $options = [])
    {
        $value = Html::getAttributeValue($model, $attribute);
    
        $field = $this->field($model, $attribute);
    
        $options['options'] = array_column($items, 'options');
        $options['prompt'] = '';
    
        return $this->staticOnly ? $field : $field->dropDownList(array_column($items, 'label', 'value'), $options);
    }
    在這個更新的版本中,我們直接將$options數組傳遞給dropDownList方法,並使用array_column從$items數組中提取標籤-值對

    回覆
    0
  • 取消回覆