Krajee
Thankful to Krajee! BUY A COFFEEor to get more out of us.

The TypeaheadBasic 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.

Important

This widget can be also installed in isolation outside this bundle if needed. In addition to using via \kartik\widgets namespace, this widget can be also installed from the yii2-widget-typeahead repository and can also be accessed via \kartik\typeahead\TypeaheadBasic namespace.

Note

The TypeaheadBasic widget is a basic implementation of the typeahead.js plugin without any suggestion engine. It uses a javascript substring matcher and Regular Expression matching to query and display suggestions.

Tip

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)

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)

The following sections describe the pre-requisites for enabling Bootstrap library specific version support in your application and other related controls/overrides.

Global Bootstrap Version


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).

Yii2 Bootstrap Dependency


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"

Override Bootstrap CSS/JS


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
                ],
            ],
        ],
    ],
    

Note

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.

Icons for Bootstrap


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:

Composer Package Manager Recommended


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.

Manual Install


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 Basic 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-',
       ],
    ];
    
  • data: array a single dimensional data array which will be used for the typeahead dropdown and filter. This is mandatory.

  • 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.

  • 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.

  • dataset: array the main Typeahead object for defining a set of data that hydrates suggestions. For TypeaheadBasic, this is a single dimensional array consisting of 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 – 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.

  • 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 Basic JQuery events. You must define events in event-name => event-function format. All events will be stacked in the sequence. Refer the plugin documentation for details. For example:

    pluginEvents = [
        "typeahead:initialized " => "function() { log("typeahead:initialized "); }",
        "typeahead:opened" => "function() { log("typeahead:opened"); }",
        "typeahead:closed" => "function() { log("typeahead:closed"); }",
        "typeahead:selected" => "function() { log("typeahead:selected"); }",
        "typeahead:autocompleted" => "function() { log("typeahead:autocompleted"); }",
    ];
    

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)

A disabled typeahead input

Scrollable dropdown input

Right to Left (RTL) input support with a scrollable dropdown

Enable display of default suggestions even when no text is searched (and on init). This is done by setting minLength to 0. You can control the number of options to show via the dataset['limit'] setting.

use kartik\widgets\TypeaheadBasic;

$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(TypeaheadBasic::classname(), [
    'data' => $data,
    'options' => ['placeholder' => 'Filter as you type ...'],
    'pluginOptions' => ['highlight'=>true],
]);

// With a model and without ActiveForm (with search term highlighting)
echo '<label class="control-label">State</label>';
echo TypeaheadBasic::widget([
    'model' => $model, 
    'attribute' => 'state_4',
    'data' => $data,
    'options' => ['placeholder' => 'Filter as you type ...'],
    'pluginOptions' => ['highlight'=>true],
]);

// Usage without a model (with search term highlighting)
echo '<label class="control-label">State</label>';
echo TypeaheadBasic::widget([
    'name' => 'state_10',
    'data' =>  $data,
    'options' => ['placeholder' => 'Filter as you type ...'],
    'pluginOptions' => ['highlight'=>true],
]);

// A disabled typeahead input
echo '<label class="control-label">State</label>';
echo TypeaheadBasic::widget([
    'name' => 'state_11',
    'data' => $data,
    'options' => ['placeholder' => 'Filter as you type ...', 'disabled' => 'disabled']
]);

// Scrollable dropdown input
echo '<label class="control-label">State</label>';
echo TypeaheadBasic::widget([
    'name' => 'state_15',
    'data' => $data,
    'scrollable' => true,
    'options' => ['placeholder' => 'Filter as you type ...'],
    'pluginOptions' => ['highlight'=>true],
]);

// Right to Left (RTL) input support with a scrollable dropdown
echo '<label class="control-label">State</label>';
echo TypeaheadBasic::widget([
    'name' => 'state_15',
    'data' => $data,
    'rtl' => true,
    'options' => ['placeholder' => 'Filter as you type ...'],
    'pluginOptions' => ['hint' => false, 'highlight' => true]
]);


// Enable default suggestions even when no text is searched
echo TypeaheadBasic::widget([
    'name' => 'state_17',
    'data' => $data,
    'dataset' => ['limit' => 10],
    'options' => ['placeholder' => 'Filter as you type ...'],
    'pluginOptions' => ['highlight' => true, 'minLength' => 0]                 
]);

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.

 
visitors to Krajee Yii2 Demos since 22-May-2017