Reputation:
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
Its showing values too not only the names.I want to show only the make names.How to do that
Upvotes: 3
Views: 431
Reputation: 9358
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();
}
Upvotes: 0
Reputation: 23740
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');
}
Upvotes: 1