3

I have created a yii2 kartik select2 widget to select multiple car models like below

<?= Select2::widget([
        'name' => 'drp-make',
        'data' => Car::getCarMakesEnglish(),
        'value' => explode(",",$model->drp_make),
        'options' => [
          'id'=>'drp-make',
          'placeholder' => 'All Makes',
          'multiple' => true
        ]
      ]); ?>

And the function to get data for the select2 like

 public static function getCarMakesEnglish(){
            $out=array();
        $makes=CarMakes::find()->select(['id','make_eng'])->all();
        foreach ($makes as $make) {
            array_push($out,array($make['id'] => $make['make_eng']));
        }
        return $out;
    }

Its working perfect.But a issue is there.please see the below picture

enter image description here

Its showing values too not only the names.I want to show only the make names.How to do that

2 Answers2

1

Because you are pushing an array to every index of the $out

array_push($out,array($make['id'] => $make['make_eng']))

you should use yii\helpers\ArrayHelper::map() instead that do this for you. Change your function getCarMakesEnglish() to the following

public static function getCarMakesEnglish()
{
    $makes = CarMakes::find()->select(['id', 'make_eng'])->all();
    return \yii\helpers\ArrayHelper::map($makes,'id','make_eng');
}
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
0

In addition to @MuhammadOmerAslam answer, you can avoid ArrayHelper::map() for simple scenario by using column()

public static function getCarMakesEnglish()
{
    return CarMakes::find()->select('make_eng')->indexBy('id')->column();
}
Insane Skull
  • 9,220
  • 9
  • 44
  • 63