25

for my drop-down list I am using this code.

<?= $form->field($medicinerequest, '[' . $id . ']' . 'medicine_name')
->DropDownList(ArrayHelper::map(\app\models\Medicine::find()
->asArray()->all(), 'id', 'medicine_name','medicine_id' ),
[ 'prompt' => 'Please Select' ])?> 

I am getting the drop-down list as in the picture. But I want it to be concatenated by hyphen(-) in one line. How can I do this?

medicine-request-drop-down

Insane Skull
  • 9,220
  • 9
  • 44
  • 63
Pawan
  • 3,864
  • 17
  • 50
  • 83

5 Answers5

61

ArrayHelper::map($array, $from, $to, $group) uses ArrayHelper::getValue() to obtain the values of $from, $to and $group. ArrayHelper::getValue() allows you to pass closures.

The anonymous function signature should be: function($array, $defaultValue).

As such you can set $to as

ArrayHelper::map(
    \app\models\Medicine::find()->asArray()->all(),
    'id',
    function($model) {
        return $model['medicine_name'].'-'.$model['medicine_id'];
    }
)
topher
  • 14,790
  • 7
  • 54
  • 70
  • Though I will stick to my solution as this can be used at many places with one declaration. But you have explained well the proper way of doing it, I will accept your answer. – Pawan Jan 06 '15 at 19:59
  • 1
    $model should be an array, not an object. So return $model['medicine_name'].'-'.$model['medicine_id']; – Diego Betto Mar 21 '16 at 12:09
  • 1
    @DiegoBetto thank you. For future reference you can edit the answer yourself to improve it. – topher Mar 21 '16 at 12:12
2

Ok I found the solution. I will welcome if there is a better solution.

I have created a function in the model Medicine.php

public function getMedicineName(){
        return $this->medicine_name .'-'.$this->medicine_id;
    }

and then in the arrayhelper replaced medicine_name with medicineName and Now I am getting what I was looking for.

Pawan
  • 3,864
  • 17
  • 50
  • 83
1

The anonymous function could be

function ($element) {
   return $element['medicine_name'] . '-'. $element['medicine_id'];
}

You can check here!

0

You can set $var in kartik Depdrop widget, as the same scenario in the Dropdown widget here We use kartik depdrop widget

<?php

        $var = ArrayHelper::map(Modelname::find()->where(['id' => $model->customer_id])->all(), 'id',
            function ($model) {
                return $model['id'] .' - '. $model['name'];
            });
        echo $form->field($model, 'id')->widget(DepDrop::classname(), [
            'data' => $var,
            'pluginOptions' => [
                'depends' => [''],
                'url' => Url::to(['#'])
            ]
        ]) ?>
eisbehr
  • 12,243
  • 7
  • 38
  • 63
0

alternatively, you can populate it from a controller esp for dependant dropdown lists; you return key=>value pairs with values concatenated from model fields.

echo "<option value='".$model->id."'>"
.$model->field1.' '
.$modle->field2.' '.$model->field3."</option>";