Answer the question
In order to leave comments, you need to log in
How to nicely add data-attribute to dropdown list in yii2?
In general, I'm trying to fasten this jquery plugin designwithpc.com/Plugins/ddSlick . It allows you to insert images into a dropdown list. To do this, you need to insert the attribute data-imagesrc="path to the image" into each option in the select.
At the moment, the dropdown list is done like this:
Html::dropDownList('league', 'id', ArrayHelper::map(League::find()->all(),'id','name'), [
'prompt' => 'Select league',
'class' => 'center-block',
'style' => 'width: 80%;',
'id' => 'leagues',
]);
public function actionGetModelsWithImages(){
$models = Models::find()->all();
$items = [];
$options = [];
foreach($models as $model){
//Формируем массив option'ов для нашего select'а
$items[$model->id] = $model->name;
$image32x32Path = "images/32x32/" . $model->name . ".png";
//Формируем массив атрибутов для каждого option'а
//Эти атрибуты(data-imagesrc, data-description) нужны для плагина
$options[$model->id] = [
'data-imagesrc' => $image32x32Path,
'data-description' => $model>name,
];
}
return Html::dropDownList('nameSelectModels', 'id', $items, [
'id' => 'selectModels',
'options' => $options,
]);
}
$.ajax({
type: 'GET',
url: 'index.php?r=prediction/getModelsWithImages',
success: function(data){
//добавляем html в нужный div
$('#leagues').html(data);
//активируем плагин
$('#selectModels').ddslick({
width: 350,
});
}
});
Answer the question
In order to leave comments, you need to log in
Prettier only if through ArrayHelper::map
For example, calling a drop-down list
$models = Models::find()->all();
return Html::dropDownList('nameSelectModels', null,
ArrayHelper::map($models, 'id', 'name'), [
'id' => 'selectModels',
'options' => ArrayHelper::map($models, 'id', 'dnames'),
]);
class Models{
...
public function getDname(){
return [
'data-imagesrc'=>"images/32x32/" . $this->name . ".png",
'data-description'=>$this->name
];
}
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question