The Typeahead widget is a Yii 2 wrapper for for the
Twitter Typeahead.js plugin with certain custom enhancements. This
input widget is a jQuery based replacement for text inputs providing search
and typeahead functionality. It is inspired by twitter.com's autocomplete search
functionality and based on Twitter's typeahead.js
, which is described as
a fast and fully-featured autocomplete library. The widget is specially styled for Bootstrap library.
The widget allows graceful degradation to a normal HTML text input, if the browser does not support JQuery.
You can setup model validation rules for a model attribute that uses TypeaheadBasic widget for input like any other field.
\kartik\widgets
namespace, this widget can be also installed from the yii2-widget-typeahead repository
and can also be accessed via \kartik\typeahead\Typeahead
namespace.
Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)
This widget is an advanced implementation of the typeahead.js plugin with the BloodHound suggestion engine and the Handlebars template compiler.
TypeaheadBasic
supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the TypeaheadBasic::bsVersion
property to one of the following.
To use with bootstrap 3 library - you can set TypeaheadBasic::bsVersion
property to any string starting with 3 (e.g. 3
or 3.3.7
or 3.x
)
To use with bootstrap 4 library - you can set TypeaheadBasic::bsVersion
property to any string starting with 4 (e.g. 4
or 4.6.0
or 4.x
)
To use with bootstrap 5 library - you can set TypeaheadBasic::bsVersion
property to any string starting with 5 (e.g. 5
or 5.1.0
or 5.x
)
Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion
property within Yii 2 application params (i.e. Yii::$app->params['bsVersion']
). To set this up, add this section of code to your application params configuration file (e.g. config/params.php
):
'params' => [ 'bsVersion' => '5.x', // this will set globally `bsVersion` to Bootstrap 5.x for all Krajee Extensions // other settings // 'adminEmail' => 'admin@example.com' ]
If TypeaheadBasic::bsVersion
property is set, in addition to Yii::$app->params['bsVersion']
, the extension level setting (TypeaheadBasic::bsVersion
property) will override the Yii::$app->params['bsVersion']
. If TypeaheadBasic::bsVersion
property is not set, and Yii::$app->params['bsVersion']
is also not set, TypeaheadBasic::bsVersion
property will default to 3.x
(i.e. Bootstrap 3.x version will be assumed as default).
You need to install one of yiisoft/yii2-bootstrap
or yiisoft/yii2-bootstrap4
or yiisoft/yii2-bootstrap5
extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion
is set to 5.x
and yiisoft/yii2-bootstrap5
is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5
extension. If bsVersion
is set to 4.x
and yiisoft/yii2-bootstrap4
is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4
extension. Similarly, if bsVersion
is set to 3.x
and yiisoft/yii2-bootstrap
is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap
extension.
To install yiisoft/yii2-bootstrap5
, add the repo to the require
section of your application's composer.json.
"yiisoft/yii2-bootstrap5": "@dev"
To install yiisoft/yii2-bootstrap4
, add the repo to the require
section of your application's composer.json.
"yiisoft/yii2-bootstrap4": "@dev"
To install yiisoft/yii2-bootstrap
, add the repo to the require
section of your application's composer.json.
"yiisoft/yii2-bootstrap": "@dev"
The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:
yii\bootstrap\BootstrapAsset
and/or yii\bootstrap\BootstrapPluginAsset
for bootstrap 3.x (bsVersion = 3
setting)
yii\bootstrap4\BootstrapAsset
and/or yii\bootstrap4\BootstrapPluginAsset
for bootstrap 4.x ( bsVersion = 4
setting)
yii\bootstrap5\BootstrapAsset
and/or yii\bootstrap5\BootstrapPluginAsset
for bootstrap 5.x (bsVersion = 5
setting)
This is controlled by the property bsDependencyEnabled
within the asset bundle (which defaults to true
). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:
Global Override: Set Yii::$app->params['bsDependencyEnabled']
to false
in your Yii 2 application config params.php
. This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.
'params' => [ 'bsDependencyEnabled' => false, // this will not load Bootstrap CSS and JS for all Krajee extensions // you need to ensure you load the Bootstrap CSS/JS manually in your view layout before Krajee CSS/JS assets // // other params settings below // 'bsVersion' => '5.x', // 'adminEmail' => 'admin@example.com' ]
Asset Bundle Specific Override: Set bsDependencyEnabled
to false
for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.
// ... 'components' => [ 'assetManager' => [ 'bundles' => [ 'kartik\form\ActiveFormAsset' => [ 'bsDependencyEnabled' => false // do not load bootstrap assets for a specific asset bundle ], ], ], ],
When setting bsDependencyEnabled
to false
, you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.
Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.
For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD
section of your view layout file, when bsVersion
is set to 4.x
or 5.x
.
Option 1: Font CSS version of Font Awesome:
<!-- on your view layout file HEAD section --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):
<!-- on your view layout file HEAD section --> <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" crossorigin="anonymous"></script>
Alternatively, you can use the FontAwesomeAsset
from the kartik-v/yii2-icons
package to load the SVG/JS version.
// on your view layout file use kartik\icons\FontAwesomeAsset; FontAwesomeAsset::register($this);
The yii2-widget-typeahead
extension can be installed automatically or manually using one of these options:
Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-widget-typeahead
via composer
package manager. Either run:
$ php composer.phar require kartik-v/yii2-widget-typeahead "dev-master"
or add:
"kartik-v/yii2-widget-typeahead": "dev-master"
to your application's composer.json
file.
You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.
The widget supports all parameters that one would pass for any Yii Input Widget. The additional parameter settings specially available for the Typeahead widget configuration are:
bsVersion
:
string | int, the bootstrap library version to be used for the extension. Refer the Bootstrap Info section for details and pre-requisites on setting this property.
To use with Bootstrap library - you can set this to any string starting with
3
(e.g. 3
or 3.3.7
or 4.x / 3.x
)
To use with bootstrap 4 - you can set this to any string starting with
4
(e.g. 4
or 4.6.0
or 4.x
)
To use with bootstrap 5 - you can set this to any string starting with
4
(e.g. 5
or 5.1.0
or 5.x
)
bsColCssPrefixes
:
array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface
. If not set will default to:.
[ 3 => [ self::SIZE_X_SMALL => 'col-xs-', self::SIZE_SMALL => 'col-sm-', self::SIZE_MEDIUM => 'col-md-', self::SIZE_LARGE => 'col-lg-', self::SIZE_X_LARGE => 'col-lg-', self::SIZE_XX_LARGE => 'col-lg-', ], 4 => [ self::SIZE_X_SMALL => 'col-', self::SIZE_SMALL => 'col-sm-', self::SIZE_MEDIUM => 'col-md-', self::SIZE_LARGE => 'col-lg-', self::SIZE_X_LARGE => 'col-xl-', self::SIZE_XX_LARGE => 'col-xl-', ], 5 => [ self::SIZE_X_SMALL => 'col-', self::SIZE_SMALL => 'col-sm-', self::SIZE_MEDIUM => 'col-md-', self::SIZE_LARGE => 'col-lg-', self::SIZE_X_LARGE => 'col-xl-', self::SIZE_XX_LARGE => 'col-xxl-', ], ];
useHandleBars
: boolean, whether to register and use the HandleBars template compiler plugin. Defaults to true
. You can set it to false
if you do not wish to use HandleBars template compiler.
defaultSuggestions
: array, the list of default values/suggestions that will be displayed on init
or when text queried is empty. This feature will be disabled if an empty array or invalid array is passed. Defaults to empty array []
.
scrollable
: boolean whether the dropdown menu is to be made scrollable. Defaults to false
.
rtl
: boolean whether the enable RTL (right to left) input support. Defaults to false
.
dataset
: array the main Typeahead object for defining a set of data that hydrates suggestions. Unlike TypeaheadBasic
, this is a multi-dimensional array for Typeahead
, with each array item being an array that consists of the following settings:
source
: JsExpression, The backing data source for suggestions. Expected to be a function with the signature
(query, syncResults, asyncResults)
. This can also be a Bloodhound instance. If not set, this will be automatically generated based on the bloodhound specific properties mentioned in the next section below.
display
: string, for a given suggestion object, determines the string representation of it. This will be
used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that
transforms a suggestion object into a string. Defaults to value
.
limit
: integer, the max number of suggestions from the dataset to display for
a given query. Defaults to 5.
async
: bool, lets the dataset know if async suggestions should be expected. Defaults to true
.
templates
: array, the templates used for rendering suggestions. Each of the templates below can be a string or a
pre-compiled template (i.e. a yii\web\JsExpression
function that takes a datum as input
and returns html as output). If not provided, defaults to <p>{{value}}</p>
notFound
or empty
, rendered when 0
suggestions are available for the given query. Can be either a HTML string or a precompiled template. If it's a precompiled template, the passed in context will contain query
.
pending
– Rendered when 0
synchronous suggestions are available but asynchronous suggestions are expected. Can be either a HTML string or a precompiled template. If it's a precompiled template, the passed in context will contain query
.
footer
– Rendered at the bottom of the dataset. Can be either a HTML
string or a precompiled template. If it's a precompiled template, the passed
in context will contain query
and isEmpty
.
header
– Rendered at the top of the dataset. Can be either a HTML string
or a precompiled template. If it's a precompiled template, the passed in
context will contain query
and isEmpty
.
suggestion
– Used to render a single suggestion. If set, this has to be a
precompiled template. The associated suggestion object will serve as the
context. Defaults to the value of displayKey
wrapped in a p
tag i.e.
<p>{{value}}</p>
. The widget includes the Handlebars
template compiler
loaded by default. Check the advanced usage section on using this.
local
: array, configuration for the local
list of datums. You must set one
of local
, prefetch
, or remote
.
prefetch
: array, configuration for the prefetch
options object. Refer
documentation for the options you can set for this parameter.
The return data must be Json encoded and converted to an associative array of the format [['value' => 'data1'], ['value' => 'data2'],...]
, where value
is the fixed key set in
display
.
remote
: array, configuration for the remote
options object. Refer
documentation for the options you can set for this parameter.
The return data must be Json encoded and converted to an associative array of the format [['value' => 'data1'], ['value' => 'data2'],...]
, where value
is the fixed key set in
displayKey
.
initialize
: boolean, whether to auto initialize the Bloodhound instance. Defaults to true
.
identify
: JsExpression, callback for identify.
datumTokenizer
: JsExpression, defaults to null
.
queryTokenizer
: JsExpression, defaults to null
.
sufficient
: integer, defaults to 5
.
sorter
: JsExpression, defaults to null
.
disabled
: boolean whether the input widget is to be entirely disabled. Defaults to false
.
readonly
: boolean whether the input widget is to be entirely readonly. Defaults to false
.
options
: array the HTML attributes for the widget input tag.
container
: array the HTML attributes for the container enclosing the input. You can set your own CSS classes here for stylin
the dropdown when using templates.
pluginOptions
: array the options for the typeahead.js
plugin. The following options can be configured:
highlight
: boolean, if true
, when suggestions are rendered, pattern matches
for the current query in text nodes will be wrapped in a strong
element.
Defaults to false
.
hint
: boolean, if false
, the typeahead will not show a hint. Defaults to true
.
minLength
: integer, the minimum character length needed before suggestions start
getting rendered. Defaults to 1
.
minLength
: array, for overriding the default class names used. See Class Names for more details.
pluginEvents
: array the Typeahead JQuery events. You must define events in
event-name
=> event-function
format. All events will be stacked in the sequence.
Refer the plugin events documentation for details. For example:
pluginEvents = [ "typeahead:active" => "function() { log("typeahead:active"); }", "typeahead:idle" => "function() { log("typeahead:idle"); }", "typeahead:open" => "function() { log("typeahead:open"); }", "typeahead:close" => "function() { log("typeahead:close"); }", "typeahead:change" => "function() { log("typeahead:change"); }", "typeahead:render" => "function() { log("typeahead:render"); }", "typeahead:select" => "function() { log("typeahead:select"); }", "typeahead:autocomplete" => "function() { log("typeahead:autocomplete"); }", "typeahead:cursorchange" => "function() { log("typeahead:cursorchange"); }", "typeahead:asyncrequest" => "function() { log("typeahead:asyncrequest"); }", "typeahead:asynccancel" => "function() { log("typeahead:asynccancel"); }", "typeahead:asyncreceive" => "function() { log("typeahead:asyncreceive"); }", ];
The return data for prefetch
or local
in the examples below must return a JSON encoded
associative array of the format [['value' => 'data1'], ['value' => 'data2'],...]
, where value
is the fixed key set in displayKey
Usage with ActiveForm and model (with search term highlighting)
With a model and without ActiveForm (with search term highlighting)
Usage without a model (with search term highlighting) and default search suggestions
A disabled typeahead input
use kartik\widgets\Typeahead $data = [ 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ]; // Usage with ActiveForm and model (with search term highlighting) echo \$form->field(\$model, 'state_3')->widget(Typeahead::classname(), [ 'options' => ['placeholder' => 'Filter as you type ...'], 'pluginOptions' => ['highlight'=>true], 'dataset' => [ [ 'local' => $data, 'limit' => 10 ] ] ]); // With a model and without ActiveForm (with search term highlighting) echo '<label class="control-label">State</label>'; echo Typeahead::widget([ 'model' => \$model, 'attribute' => 'state_4', 'options' => ['placeholder' => 'Filter as you type ...'], 'pluginOptions' => ['highlight'=>true], 'dataset' => [ [ 'local' => $data, 'limit' => 10 ] ] ]); // Usage without a model (with search term highlighting) echo '<label class="control-label">State</label>'; echo Typeahead::widget([ 'name' => 'state_10', 'options' => ['placeholder' => 'Filter as you type ...'], 'pluginOptions' => ['highlight'=>true], 'dataset' => [ [ 'local' => $data, 'limit' => 10 ] ] ]); // A disabled typeahead input echo '<label class="control-label">State</label>'; echo Typeahead::widget([ 'name' => 'state_11', 'disabled' => true, 'options' => [ 'placeholder' => 'Filter as you type ...', ], 'dataset' => [ [ 'local' => $data, 'limit' => 10 ] ] ]);
The return data for prefetch
or remote
in the examples below must be return a JSON encoded
associative array of the format [['value' => 'data1'], ['value' => 'data2'],...]
, where value
is the fixed key set in displayKey
Enabling default suggestions on init or when no text is searched. You must set the defaultSuggestions
property to a valid array of values you wish to show.
Prefetch data via controller action along with a scrollable dropdown
Right to Left (RTL) input support
Defines a custom template with a Handlebars
compiler for rendering suggestions
Two datasets that are prefetched, stored, and searched on the client
Prefetches some data then relies on remote requests (ajax) via Controller action for suggestions when prefetched data is insufficient.
use kartik\widgets\Typeahead; use yii\helpers\Url; // Enabling default suggestions on init or when no text is searched echo '<label class="control-label">State</label>'; echo Typeahead::widget([ 'name' => 'state_12', 'options' => ['placeholder' => 'Filter as you type ...'], 'defaultSuggestions' => $data, // you can set it to your own array 'pluginOptions' => ['highlight' => true], 'dataset' => [ [ 'local' => $data, 'limit' => 20 ] ] ]); // Prefetch data via controller action along with a scrollable dropdown echo '<label class="control-label">Select Country</label>'; echo Typeahead::widget([ 'name' => 'country_1', 'options' => ['placeholder' => 'Filter as you type ...'], 'scrollable' => true, 'pluginOptions' => ['highlight'=>true], 'dataset' => [ [ 'prefetch' => Url::to(['site/country-list']), 'limit' => 10 ] ] ]); // Right to Left (RTL) input support echo '<label class="control-label">Select Country</label>'; echo Typeahead::widget([ 'name' => 'country_30', 'options' => ['placeholder' => 'Filter as you type ...'], 'scrollable' => true, 'rtl' => true, 'pluginOptions' => ['hint' => false, 'highlight' => true], 'dataset' => [ [ 'prefetch' => Url::to(['site/country-list']), 'limit' => 10 ] ] ]); // Defines a custom template with a <code>Handlebars</code> compiler for rendering suggestions echo '<label class="control-label">Select Repository</label>'; $template = '<div><p class="repo-language">{{language}}</p>' . '<p class="repo-name">{{name}}</p>' . '<p class="repo-description">{{description}}</p></div>'; echo Typeahead::widget([ 'name' => 'twitter_oss', 'options' => ['placeholder' => 'Filter as you type ...'], 'dataset' => [ [ 'prefetch' => $baseUrl . '/samples/repos.json', 'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('value')", 'display' => 'value', 'templates' => [ 'notFound' => '<div class="text-danger" style="padding:0 8px">Unable to find repositories for selected query.</div>', 'suggestion' => new JsExpression("Handlebars.compile('{$template}')") ] ] ] ]); // Two datasets that are prefetched, stored, and searched on the client echo Typeahead::widget([ 'name' => 'sports', 'options' => ['placeholder' => 'Filter as you type ...'], 'pluginOptions' => ['highlight'=>true], 'dataset' => [ [ 'prefetch' => $baseUrl . '/samples/nba.json', 'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('value')", 'display' => 'value', 'templates' => [ 'header' => '<h3 class="league-name">NBA Teams</h3>' ] ], [ 'prefetch' => $baseUrl . '/samples/nhl.json', 'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('value')", 'display' => 'value', 'templates' => [ 'header' => '<h3 class="league-name">NHL Teams</h3>' ] ] ] ]); /** * Prefetches some data then relies on remote requests (ajax) via Controller action * for suggestions when prefetched data is insufficient. * The json encoded prefetch source is: * [{value:"Andorra"}, {value:"United Arab Emirates"}, {value:"Afghanistan"}, * {value:"Antigua and Barbuda"}, {value:"Anguilla"}, {value:"Albania"}] */ echo Typeahead::widget([ 'name' => 'country', 'options' => ['placeholder' => 'Filter as you type ...'], 'pluginOptions' => ['highlight'=>true], 'dataset' => [ [ 'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('value')", 'display' => 'value', 'prefetch' => $baseUrl . '/samples/countries.json', 'remote' => [ 'url' => Url::to(['site/country-list']) . '?q=%QUERY', 'wildcard' => '%QUERY' ] ] ] ]); /** * Your controller action to fetch the list */ public function actionCountryList($q = null) { $query = new Query; $query->select('name') ->from('country') ->where('name LIKE "%' . $q .'%"') ->orderBy('name'); $command = $query->createCommand(); $data = $command->queryAll(); $out = []; foreach ($data as $d) { $out[] = ['value' => $d['name']]; } echo Json::encode($out); }
Comments & Discussion
Note
You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.
The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.