xpbl4/yii2-typeahead-widget

Yii2 wrapper for the Twitter Typeahead widget

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

This package is not auto-updated.

Last update: 2024-12-21 23:08:51 UTC


README

Latest Version Software License Total Downloads

Typeahead widget allows to create typeahead dropdown lists

Installation

The preferred way to install this extension is through composer.

Either run

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

or add

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

to the require section of your composer.json file.

Usage

Once the extension is installed, simply use it in your code by:

<?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()
        ]
    ]
]);
?>

Note the use of the custom wildcard. It is required as if we use typeahead.js default's wildcard (%QUERY), Yii2 will automatically URL encode it thus making the wrong configuration for token replacement.

The results need to be JSON encoded as specified on the plugin documentation. The following is an example of a custom Action class that you could plug to any Controller:

And how to add action on your Controller class:

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