Dropdown list customisation

Hi,

I would like to have a dropdown list in a form that show two column from a table and indexes by one of them.

For example in a table with two attributes ‘id’ and ‘name’, the dropdown would show something like this :

‘id’ - ‘name’

I tried this :




<?= $form->field($model, 'bpr_id')->dropdownList(bpr::findBySql('SELECT id + ' - ' + name  FROM  bpr ')->indexBy('bpr_id')->column(),

['prompt'=>'Selectionez la BPR'])?>



and this :




<?= $form->field($model, 'bpr_id')->dropdownList(bpr::find()->select(['id' , 'name'])->indexBy('bpr_id')->column()

,['prompt'=>'Selectionez la BPR'])?>



Neither of them worked.

Any suggestion ?

Firstly this Dropdownlist is missing some parts, thats ok, i’d first try to make the dropdownlist actually work.

you need to change the form field and add the


ArrayHelper

class for that, so in your case (just to get either ‘id’ or ‘name’);




<?= $form->field($model, 'bpr_id')->dropDownList(

        ArrayHelper::map(bpr::find()->all(), 'id', 'name' ),

        ['prompt'=>'Selectionez la BPR']

    ) ?>

ofcourse you need to use the arrayhelper class in the form so at the top.


use yii\helpers\ArrayHelper;

Sadly i do not know how to populate each field with more than one var(either name or id).

but this should give you a lot more ability, MAYBE you can try and put the id and name in a $var but i’m not sure.

Update to what i said before, i Found the way to do it,

to set the last part of the thing you want, list: id/name.

change the:




<?= $form->field($model, 'bpr_id')->dropDownList(

        ArrayHelper::map(bpr::find()->all(), 'id', 'name' ),

        ['prompt'=>'Selectionez la BPR']

    ) ?>

to ->


<?= $form->field($model, 'bpr_id')->dropDownList(

        ArrayHelper::map(bpr::find()->all(), 'id',

        function($model, $defaultValue) {

        		return $model->id.' - '.$model->name;

    		}

 ),

        ['prompt'=>'Selectionez la BPR']

    ) ?>



This will give you the List with id - name for each list item,

Goodluck :)

Thank you.