Home » Php » php – Yii2 kartik select2 widget showing values too issue

php – Yii2 kartik select2 widget showing values too issue

Posted by: admin February 25, 2020 Leave a comment


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' => [
          'placeholder' => 'All Makes',
          'multiple' => true
      ]); ?>

And the function to get data for the select2 like

 public static function getCarMakesEnglish(){
        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

How to&Answers:

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');


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();