我在yii2工作。我有一种形式。其中我有一个下拉列表。我需要显示所有下拉选项的名称和图像与选项组。
正在显示图像和名称。但是如何用选项组显示所有的选项呢?
查看文件:
<div class="col-xs-6 col-md-5">
<?= $form->field($model,'targetfish_id')->dropDownList(ArrayHelper::map(Targetfish::find()->all(),'id','image'),
['multiple'=>'multiple']) ?>
</div>
查看文件脚本:
<?php
$this->registerJs('
function formatState (fish) {
if (!fish.id) { return fish.text; }
var $fish = $(
"<span><img src=/www/target_fish_pic/"+fish.text+ " class=img-flag style=width:50px />"+ fish.text +"</span>"
);
return $fish;
};
$("#boatinformation-targetfish_id").select2({
placeholder: "Select Targeted Fish",
templateResult: formatState,
templateSelection: formatState,
});
$(document).ready(function(){
$("#boatinformation-in_water_slip").change();
});
$("#boatinformation-in_water_slip").on("change",function(){
if( $(this).val()==="0"){
$(".slip_controls").hide()
$(".guest_controls").show()
}
else{
$(".slip_controls").show()
$(".guest_controls").hide()
}
});
');
如何从上面的代码创建选项组?而且在下拉值中,它打印图像名称而不是值(因为这行-> map(Targetfish::find()->all(),'id','image')
)。我可以记下我的名字和照片吗?
Select2内置AJAX支持,使用jQuery的AJAX方法。这将有助于您显示您的要求的图像。
你可以点击下面的链接查看更多信息。
https://select2.github.io/examples.html data-ajax
<script>
function fmtState (state) {
if (!state.id) { return state.text; }
var $state = $(
'<span>'+
'<img src="images/flags/' +
state.element.value.toLowerCase() +
'.png" class="img-flag" /> ' +
state.text +
'</span>'
);
return $state;
}
</script>
<div class="input-control" data-template-result="fmtState" data-role="select">
<select>
<option>option</option>
...
<option>option</option>
</select>
</div>