xpbl4/yii2-typeahead-widget

Twitter Typeahead widget 的 Yii2 封装

v1.0.1 2023-08-27 23:15 UTC

This package is not auto-updated.

Last update: 2024-09-28 22:05:20 UTC


README

Latest Version Software License Total Downloads

Typeahead widget 允许创建自动完成下拉列表

安装

通过 composer 安装此扩展是首选方式。

运行以下命令

php composer.phar require --prefer-dist xpbl4/yii2-typeahead-widget "*"

或者

"xpbl4/yii2-typeahead-widget": "*"

将以下内容添加到你的 composer.json 文件的 require 部分。

使用方法

安装扩展后,只需在代码中简单使用即可

<?php
$engine = new \xpbl4\typeahead\Bloodhound([
    'name' => 'countriesEngine',
    'pluginOptions' => [
        'datumTokenizer' => new \yii\web\JsExpression("Bloodhound.tokenizers.obj.whitespace('name')"),
        'queryTokenizer' => new \yii\web\JsExpression("Bloodhound.tokenizers.whitespace"),
        'remote' => [
            'url' => Url::to(['country/autocomplete', 'query'=>'QRY']),
        ]
    ]
]);

echo \xpbl4\typeahead\Typeahead::widget([
    'id' => 'exampleInput',
    'name' => 'test',
    'options' => ['class' => 'form-control', 'prompt' => 'Start type to find...'],
    'engines' => [ $engine ],
    'pluginOptions' => [
        'highlight' => true,
        'minLength' => 3
    ],
    'pluginEvents' => [
        'typeahead:selected' => 'function (e, o) { console.log("event \'selected\' occured on " + o.value + "."); }'
    ],
    'data' => [
        [
            'name' => 'countries',
            'displayKey' => 'value',
            'source' => $engine->getAdapterScript()
        ]
    ]
]);
?>

注意自定义的 wildcard 使用。如果我们使用 typeahead.js 默认的 wildcard (%QUERY),Yii2 会自动进行 URL 编码,从而可能导致 token 替换配置错误。

结果需要按照 插件文档 中指定的方式进行 JSON 编码。以下是一个自定义 Action 类的示例,您可以将它连接到任何 Controller

以及如何在您的 Controller 类中添加操作

public function actions()
{
	return [
		'autocomplete' => [
			'class' => 'xpbl4\typeahead\actions\AutocompleteAction',
			'model' => Country::tableName(),
			'field' => 'name'
		]
	];
}