yii2 dropdown items custom attribute

I have a small problem, need to have drop down in Yii2 from model and set data attribute with every item like

<option "value"=25 "data"=21 >test</option>

here is my current code.

<?= $form->field($modelsOrderdetail, "[{$i}]item_id")->dropDownList(\yii\helpers\ArrayHelper::map(

                            item::find()-&gt;all(), 'id','title'//, 'category.title'


                            ),  ['options' =&gt; [6 =&gt; ['disabled' =&gt; true], 'class' =&gt; 'form-control']] ) ?&gt;

Data could be any attr in item model.

Any help will be highly appreciated.

loop over you items and create another $options array and pass that to the options




<?php

// use the ArrayHelper

use yii\helpers\ArrayHelper;


// create item map for option tags

$items = ArrayHelper::map(item::find()->all(), 'id','title');


// list of disabled items

$disabled = [6,7];


// options with additional html attrs added

$options = [];

foreach (item::find()->all() as $i) {

    $options[$m->id] = ['data-id' => $m->id, 'class' => 'form-control'];

    if (in_array($m->id, $disabled)) {

        $options[$m->id]['disabled'] = true;

    }

}


<?= $form->field($modelsOrderdetail, "[{$i}]item_id")->dropDownList($items, ['options' => $options] ) ?>

note: I have not tested it make changes accordingly

1 Like