2amigos / yii2-type-ahead-widget
此包已被废弃,不再维护。未建议替代包。
Yii框架的bootstrap typeahead小部件
3.0.0
2019-04-08 15:52 UTC
Requires
- bower-asset/typeahead.js: ~0.11.0
- yiisoft/yii2: ~2.0.13
- yiisoft/yii2-bootstrap: ~2.0.0
Requires (Dev)
- phpunit/phpunit: ~5.0
README
渲染一个 Twitter Typeahead.js Bootstrap插件 小部件。
安装
通过 composer 安装此扩展是首选方式。
运行以下命令
$ composer require 2amigos/yii2-type-ahead-widget:~2.0
或向你的 composer.json
文件的 require
部分添加以下内容
"2amigos/yii2-type-ahead-widget": "~2.0"
使用方法
使用模型和 remote
配置
use dosamigos\typeahead\Bloodhound;
use dosamigos\typeahead\TypeAhead;
use yii\helpers\Url;
<?php
$engine = new Bloodhound([
'name' => 'countriesEngine',
'clientOptions' => [
'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']),
'wildcard' => 'QRY'
]
]
]);
?>
<?= $form->field($model, 'country')->widget(
TypeAhead::className(),
[
'options' => ['class' => 'form-control'],
'engines' => [ $engine ],
'clientOptions' => [
'highlight' => true,
'minLength' => 3
],
'clientEvents' => [
'typeahead:selected' => 'function (e, o) { console.log("event \'selected\' occured on " + o.value + "."); }'
],
'dataSets' => [
[
'name' => 'countries',
'displayKey' => 'value',
'source' => $engine->getAdapterScript()
]
]
]
);?>
注意自定义 wildcard
的使用。因为它要求我们使用 typeahead.js
默认的通配符(%QUERY
),如果Yii2自动进行URL编码,则可能导致token替换配置错误。
结果需要按照 插件文档 中的说明进行JSON编码。以下是一个示例自定义 Action
类,你可以将其连接到任何 Controller
namespace frontend\controllers\actions;
use yii\base\Action;
use yii\helpers\Json;
use yii\base\InvalidConfigException;
class AutocompleteAction extends Action
{
public $tableName;
public $field;
public $clientIdGetParamName = 'query';
public $searchPrefix = '';
public $searchSuffix = '%';
public function init()
{
if($this->tableName === null) {
throw new InvalidConfigException(get_class($this) . '::$tableName must be defined.');
}
if($this->field === null) {
throw new InvalidConfigException(get_class($this) . '::$field must be defined.');
}
parent::init();
}
public function run()
{
$value = $this->searchPrefix . $_GET[$this->clientIdGetParamName] . $this->searchSuffix;
$rows = \Yii::$app->db
->createCommand("SELECT {$this->field} AS value FROM {$this->tableName} WHERE {$this->field} LIKE :field ORDER BY {$this->field}")
->bindValues([':field' => $value])
->queryAll();
echo Json::encode($rows);
}
}
以及如何在你的 Controller
类中配置它
public function actions()
{
return [
'autocomplete' => [
'class' => 'frontend\controllers\actions\AutocompleteAction',
'tableName' => Country::tableName(),
'field' => 'name'
]
];
}
主题
Twitter Typeahead.js Bootstrap插件 不对下拉列表、提示或输入字段进行样式设计。它是这样做的,以便你可以自定义它,使其适合你的应用程序。
我们包含了一个样式表,其中包含与 form-control
bootstrap类匹配的提示和其他调整,以便您可以轻松识别类并对其进行样式设计。
测试
$ ./vendor/bin/phpunit
贡献
请参阅 CONTRIBUTING 获取详细信息。
致谢
许可
The BSD License (BSD)。请参阅 License File 获取更多信息。
web开发从未如此有趣
www.2amigos.us