JQuery的自动填充功能支持自动填充结果中的类别。如下面的链接(只需输入字母' a'):
https://jqueryui.com/resources/demos/autocomplete/categories.html
Yii2的jQuery自动填充小部件有一个source
参数,可以为自动完成的结果接收数组。但是当我给它一个多维数组时,试图获得类似上面链接的类别,它会破坏自动完成。见下文:
AutoComplete::widget([
'name' => 'search_terms',
'options' => [
'style' => 'width:100%;',
],
'clientOptions' => [
'source' => ['NA' => ['USA', 'CAN'], 'EUR' => ['RUS', 'SPN']],
],
])
如何在Yii2的自动填充小部件中使用类别?
答案 0 :(得分:2)
这种类型的小部件只是Javascript插件的包装,允许您使用PHP代码注册它(使用PHP数组而不是Javascript对象配置属性等)。如果您调查AutoComplete窗口小部件和父类的来源,您将找不到source
属性的任何特殊处理。这意味着你需要遵循jQuery UI插件文档,点击"查看源代码"链接here以显示代码。 JS部分看起来像这样:
<script>
$( function() {
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
var li;
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
li = that._renderItemData( ul, item );
if ( item.category ) {
li.attr( "aria-label", item.category + " : " + item.label );
}
});
}
});
var data = [
{ label: "anders", category: "" },
{ label: "andreas", category: "" },
{ label: "antal", category: "" },
{ label: "annhhx10", category: "Products" },
{ label: "annk K12", category: "Products" },
{ label: "annttop C13", category: "Products" },
{ label: "anders andersson", category: "People" },
{ label: "andreas andersson", category: "People" },
{ label: "andreas johnson", category: "People" }
];
$( "#search" ).catcomplete({
delay: 0,
source: data
});
} );
</script>
正如您所看到的,您传递的类别错误。试试这个:
'source' => [
['label' => 'USA', 'category' => 'NA'],
['label' => 'CAN', 'category' => 'NA'],
['label' => 'RUS', 'category' => 'EUR'],
['label' => 'RUS', 'category' => 'SPN'],
],
同样对于这种情况,您可能需要包含额外的JS(上面的插件注册)来完全重现示例。