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

The Select2 widget is a Yii 2 wrapper for the Select2 jQuery plugin. This input widget is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results. The widget is specially styled for Bootstrap library. The widget allows graceful degradation to a normal HTML select or text input, if the browser does not support JQuery. You can setup model validation rules for a model attribute that uses Select2 widget for input like any other field.

New release v2.0: The widget has been revamped and upgraded to v2.0 to implement Select2 plugin release v4.0. Select2 release v4.0 is a major rewrite over Select2 v4.x / 3.x and hence quite a few enhancements or changes should be expected. The following new functionalities and changes should be expected with this release.

  • New theme property that allows you to set themes in Select2 to style your widget.

  • A brand new theme by Krajee Select2::THEME_KRAJEE is now available and specially styled for yii2-widget-select2. This will help achieve various widget specific enhancements and features. This theme matches the Bootstrap library styling with various enhancements.

  • Additional themes provided in form of Select2::THEME_DEFAULT, Select2::THEME_CLASSIC, and Select2::THEME_BOOTSTRAP. One can add their own custom theme and configure the widget

  • No more query plugin property needed. It is also not mandatory to configure data even if you have not set tags or query or ajax. Widget will intelligently evaluate the properties and default list values.

  • Enhanced tagging support. Use it just like a multiple select but with taggable values. In addition, one can create tags on the fly.

  • Enhanced ajax support. Refer the usage demos for details.

  • The initSelection method of Select2 3.5.x plugin is obsolete/removed. New initValueText property is been provided with the Select2 widget to cater to this (e.g. for ajax based loading).

  • Ability to disable selective option values in the Select2 dropdown OR add HTML attributes to selective options.

  • Enhancement by Krajee to disable the search box to use like a normal select.

  • Enhancements to locales and translations. Allow multiple language Select2 widgets on the same page.

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-select2 repository and can also be accessed via \kartik\select2\Select2 namespace.

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)

Select2 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 Select2::bsVersion property to one of the following.

  • To use with bootstrap 3 library - you can set Select2::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 Select2::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 Select2::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 Select2::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (Select2::bsVersion property) will override the Yii::$app->params['bsVersion']. If Select2::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, Select2::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-select2 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-select2 via composer package manager. Either run:

$ php composer.phar require kartik-v/yii2-widget-select2 "dev-master"

or add:

"kartik-v/yii2-widget-select2": "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 Select2 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 the select option data items. The array keys are option values, and the array values are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). For each sub-array, an option group will be generated whose label is the key associated with the sub-array. If you have a list of data models, you may convert them into the format described above using \yii\helpers\ArrayHelper::map().

  • language: string the locale ID (e.g. fr, de) for the language to be used by the Select2 Widget. If this property not set, then the current application language will be used (i.e. Yii::$app->language). Note:With release v4.0 of the Select2 plugin, you can have multiple language Select2 widgets on the same page.

  • theme: string the theme to be used for the Select2 widget. The following themes are available inbuilt with this widget:

    • Select2::THEME_KRAJEE_BS5 or 'krajee-bs5': This theme has been created specially by Krajee which matches bootstrap 4 styles and adds various enhancements to work with Yii2 Select2 widget. This will be set as the default theme, if bsVersion is set to 5.x.

    • Select2::THEME_KRAJEE_BS4 or 'krajee-bs4': This theme has been created specially by Krajee which matches bootstrap 4 styles and adds various enhancements to work with Yii2 Select2 widget. This will be set as the default theme, if bsVersion is set to 4.x.

    • Select2::THEME_KRAJEE or 'krajee': This theme has been created specially by Krajee which matches Bootstrap library styles and adds various enhancements to work with Yii2 Select2 widget. This will be set as the default theme, if bsVersion is set to 3.x.

    • Select2::THEME_MATERIAL or 'material': This theme is available since v2.1.5 and resembles the Google Material form input design.

    • Select2::THEME_DEFAULT or 'default': The default inbuilt Select2 theme.

    • Select2::THEME_CLASSIC or 'classic': The classic Select2 theme.

    • Select2::THEME_BOOTSTRAP or 'bootstrap': The Bootstrap library Select2 theme from github.com/fk/select2-bootstrap-theme.

    The theme property if not set, will automatically default to one of the following themes based on your bootstrap version:

    • Select2::THEME_KRAJEE_BS5 for Bootstrap 5.x.

    • Select2::THEME_KRAJEE_BS4 for Bootstrap 4.x.

    • Select2::THEME_KRAJEE for Bootstrap 3.x.

    You can define your own custom theme by setting this property and rendering the theme specific CSS on your page. Refer to the Select2 plugin documentation for details on creating themes.

  • changeOnReset: bool whether to trigger change for Select2 input on form reset so the Select2 value is rightly reset. Defaults to true.

  • hideSearch: bool whether to hide the search control and display a simple select. Defaults to false.

  • maintainOrder: bool whether to maintain the order of tag / option selected for a multiple select. Defaults to true.

  • showToggleAll: bool whether to show the toggle all button for selection all options in a multiple select. Defaults to true.

  • toggleSettings: array, the toggle all button settings for selecting/unselecting all the options. This is applicable only for * multiple select. The following array key properties can be set:

    • selectLabel: string, the markup to be shown to select all records. Defaults to:

      • <i class="far fa-square"></i> Select all when Select2::bsVersion is set to 4.x or 5.x, OR

      • <i class="fas fa-unchecked"></i> Select all when Select2::bsVersion is set to 3.x.

    • unselectLabel: string, the markup to be shown to select all records. Defaults to:

      • <i class="far fa-check-square"></i> Unselect all when Select2::bsVersion is set to 4.x or 5.x, OR

      • <i class="fas fa-checked"></i> Unselect all when Select2::bsVersion is set to 3.x.

    • selectOptions: array, the HTML attributes for the container wrapping the select label. Defaults to []

    • unselectOptions: array, the HTML attributes for the container wrapping the unselect label. Defaults to []

    • options: array, the HTML attributes for the toggle button container. Defaults to ['class' => 's2-togall-button']

  • initValueText: string, the text to displayed in Select2 widget for the initial value. This is useful and applicable when you are using the widget with ajax loaded data AND/OR you are not providing the data. Check the ajax usage section for an example.

  • addon: array Adds an input group addon to the Select2 widget

    • prepend: array|string the prepend addon configuration. If set as a string, will be rendered as is. If set as an array, you can set the following keys:

      • content: string the prepend addon content

      • asButton: boolean whether the addon is a button or button group. Defaults to false.

    • append: array|string the append addon configuration. If set as a string, will be rendered as is. If set as an array, you can set the following keys:

      • content: string the append addon content

      • asButton: boolean whether the addon is a button or button group. Defaults to false.

    • groupOptions: array HTML options for the input group

    • contentBefore: string content placed before addon. This is not HTML encoded.

    • contentAfter: string content placed after addon. This is not HTML encoded.

  • size: string size of the Select2 input, must be one of the size constants

    • LARGE or 'lg'

    • MEDIUM or 'md'

    • SMALL or 'sm'

  • 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 input tag. The following options are important:

    • multiple: boolean whether multiple or single item should be selected.

    • placeholder or prompt: string placeholder text for the select item. To set a placeholder, you must set one of placeholder or prompt.

  • pluginLoading: boolean, whether to show a loading progress indicator in place of the input before plugin is completely loaded. Defaults to true.

  • pluginOptions: array the Select2 JQuery plugin options. Refer the plugin options documentation for details. The widget automatically reacts to the following pluginOptions

    • data: If you set this within the pluginOptions, it will override the data set at widget level. A hidden text input will be rendered instead of a HTML select in this case.

    • ajax: If you wish to use ajax set this option instead of a separate ajax function.

    • tags: If you wish to display tags selection, use this option. Usually you must set this to true with the options['multiple'] enabled. However you can set this to true to add custom tags for both single and multiple select. When options['multiple'] is enabled, the tags work very similar to a multiple select input and reads and sends data as an array.

  • pluginEvents: array the Select2 JQuery events. You must define events in event-name => event-function format. All events will be stacked in the sequence. Refer the plugin options documentation for details. For example:

    pluginEvents = [
        "change" => "function() { log('change'); }",
        "select2:opening" => "function() { log('select2:opening'); }",
        "select2:open" => "function() { log('open'); }",
        "select2:closing" => "function() { log('close'); }",
        "select2:close" => "function() { log('close'); }",
        "select2:selecting" => "function() { log('selecting'); }",
        "select2:select" => "function() { log('select'); }",
        "select2:unselecting" => "function() { log('unselecting'); }",
        "select2:unselect" => "function() { log('unselect'); }"
    ];
    
Basic usage of single and multiple select with Select2 widget with model, ActiveForm or without a model.
 

Usage with ActiveForm and model. Check the model and active form validation outcomes & messages styled via bootstrap contextual classes. For example select a value and unselect it using the clear icon.


 

With a model and without ActiveForm


 

Without model and implementing a multiple select


 

A disabled select2 list input

use kartik\select2\Select2

// Usage with ActiveForm and model
echo $form->field($model, 'state_1')->widget(Select2::classname(), [
    'data' => $data,
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);

// With a model and without ActiveForm
echo Select2::widget([
    'model' => $model,
    'attribute' => 'state_2',
    'data' => $data,
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);

// Without model and implementing a multiple select
echo '<label class="control-label">Provinces</label>';
echo Select2::widget([
    'name' => 'state_10',
    'data' => $data,
    'options' => [
        'placeholder' => 'Select provinces ...',
        'multiple' => true
    ],
]);

// A disabled select2 list input
echo '<label class="control-label">State</label>';
echo Select2::widget([
    'name' => 'state_11',
    'data' => $data,
    'disabled' => true
]);
Advanced usages of the Select2 widget.
 

Templating example of formatting each list element


 

Disable specific values for selection (for example disable third and fourth value).


Using a select2 widget inside a bootstrap modal dialog. Note the dropdownParent property in pluginOptions. You can set it to the Modal container identifier to ensure the Select2 dropdown is displayed correctly in the container.


Using a select2 widget inside a Krajee Yii2 PopoverX dialog. Note the dropdownParent property in pluginOptions. You can set it to the PopoverX container identifier to ensure the Select2 dropdown is displayed correctly in the container.


 

Render a simple select by hiding the search control.


 
 

Using localization. For example set the widget to use Russian language and French Language. You can use multiple widgets with different languages on the same page with release 4.0 of Select2 plugin.


 

 

 

Using themes. By default the widget uses one of the specially created themes by Krajee based on your bootstrap version.

  • Select2::THEME_KRAJEE_BS5 for bsVersion = '5.x'

  • Select2::THEME_KRAJEE_BS4 for bsVersion = '4.x'

  • Select2::THEME_KRAJEE for bsVersion = '3.x'

You can also use one of the other themes available: THEME_MATERIAL, THEME_DEFAULT, THEME_CLASSIC or THEME_BOOTSTRAP, or build your own custom theme and set in here.


 
 

 
 

 
 

 
 
use kartik\select2\Select2;
use kartik\popover\PopoverX;
use yii\bootstrap5\Modal;

// Templating example of formatting each list element
$url = \Yii::$app->urlManager->baseUrl . '/images/flags/';
$format = <<< SCRIPT
function format(state) {
    if (!state.id) return state.text; // optgroup
    src = '$url' +  state.id.toLowerCase() + '.png'
    return '<img class="flag" src="' + src + '"/>' + state.text;
}
SCRIPT;
$escape = new JsExpression("function(m) { return m; }");
$this->registerJs($format, View::POS_HEAD);
echo '<label class="control-label">Provinces</label>';
echo Select2::widget([
    'name' => 'state_12',
    'data' => $data,
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'templateResult' => new JsExpression('format'),
        'templateSelection' => new JsExpression('format'),
        'escapeMarkup' => $escape,
        'allowClear' => true
    ],
]);

// Disable specific values for selection (for example disable third and fourth value)
echo Select2::widget([
    'name' => 'kv-type-01',
    'data' => [1 => "First", 2 => "Second", 3 => "Third", 4 => "Fourth", 5 => "Fifth"],
    'options' => [
        'placeholder' => 'Select a type ...',
        'options' => [
            3 => ['disabled' => true],
            4 => ['disabled' => true],
        ]
    ],
]);

// Using a select2 widget inside a modal dialog
Modal::begin([
    'options' => [
        'id' => 'kartik-modal',
        'tabindex' => false // important for Select2 to work properly
    ],
    'title' => 'Select2 Inside Modal',
    'toggleButton' => ['label' => 'Show Modal', 'class' => 'btn btn-lg btn-primary'],
]);
echo Select2::widget([
    'name' => 'state_40',
    'data' => $data,
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'allowClear' => true,
        'dropdownParent' => '#kartik-modal'
    ],
]);
Modal::end();

// Using a select2 widget inside a Krajee Yii2 PopoverX dialog
PopoverX::begin([
    'id' => 'kartik-popover',
    'header' => 'Select2 Inside PopoverX',
    'toggleButton' => ['label' => 'Show PopoverX', 'class' => 'btn btn-lg btn-primary'],
]);
echo Html::textInput('Address', '',  ['class' => 'form-control mb-3', 'placeholder' => 'Enter address...']);
echo Select2::widget([
    'name' => 'state_41',
    'data' => $data,
    'options' => ['placeholder' => 'Select a state ...', 'autocomplete' => 'new-password'],
    'pluginOptions' => [
        'allowClear' => true,
        'dropdownParent' => '#kartik-popover'
    ],
]);
echo Html::textInput('City', '',  ['class' => 'form-control mt-3', 'placeholder' => 'Enter city...']);
echo Html::textInput('Zip', '',  ['class' => 'form-control mt-3', 'placeholder' => 'Enter zity...']);
PopoverX::end();
PopoverX::end();
// Render a simple select by hiding the search control.
echo '<label class="control-label">Status</label>';
echo Select2::widget([
    'name' => 'status',
    'hideSearch' => true,
    'data' => [1 => 'Active', 2 => 'Inactive'],
    'options' => ['placeholder' => 'Select status...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);

// Localization - set widget language to translate messages in your local language
// russian
echo Select2::widget([
    'name' => 'kv_lang_select1',
    'language' => 'ru',
    'data' => $data,
    'options' => ['placeholder' => 'Выберите состояние ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);
// french
echo Select2::widget([
    'name' => 'kv_lang_select2',
    'language' => 'fr',
    'data' => $data,
    'options' => ['placeholder' => 'Sélectionnez un état ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);

// Using themes
// Krajee Bootstrap 5.x / 4.x Theme
echo Select2::widget([
    'bsVersion' => '4.x',
    'name' => 'kv_theme_select1a',
    'data' => $data,
    'theme' => Select2::THEME_KRAJEE, // this is the default if theme is not set
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);

// Krajee Bootstrap 3.x Theme
echo Select2::widget([
    'bsVersion' => '3.x',
    'name' => 'kv_theme_select1b',
    'data' => $data,
    'theme' => Select2::THEME_KRAJEE, // this is the default if theme is not set
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);

<div class="row">
    <div class="col-sm-6">
       <label>Theme MATERIAL (Single)</label>
        <?php
        echo Select2::widget([
            'name' => 'kv_theme_material_1',
            'data' => $data,
            'theme' => Select2::THEME_MATERIAL,
            'options' => ['placeholder' => 'Select a state ...', 'autocomplete' => 'off'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]);
        ?>
    </div>
    <div class="col-sm-6">
       <label>Theme MATERIAL (Multiple)</label>
        <?php
        echo Select2::widget([
            'name' => 'kv_theme_material_2',
            'data' => $data,
            'theme' => Select2::THEME_MATERIAL,
            'options' => ['placeholder' => 'Select a state ...', 'multiple' => true, 'autocomplete' => 'off'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]);
        ?>
    </div>
</div>
<br>
<div class="row">
    <div class="col-sm-6">
       <label>Theme BOOTSTRAP (Single)</label>
        <?php
        echo Select2::widget([
            'name' => 'kv_theme_bootstrap_1',
            'data' => $data,
            'theme' => Select2::THEME_BOOTSTRAP,
            'options' => ['placeholder' => 'Select a state ...', 'autocomplete' => 'off'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]);
        ?>
    </div>
    <div class="col-sm-6">
       <label>Theme BOOTSTRAP (Multiple)</label>
        <?php
        echo Select2::widget([
            'name' => 'kv_theme_bootstrap_2',
            'data' => $data,
            'theme' => Select2::THEME_BOOTSTRAP,
            'options' => ['placeholder' => 'Select a state ...', 'multiple' => true, 'autocomplete' => 'off'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]);
        ?>
    </div>
</div>
<br>
<div class="row">
    <div class="col-sm-6">
       <label>Theme CLASSIC (Single)</label>
        <?php
        echo Select2::widget([
            'name' => 'kv_theme_classic_1',
            'data' => $data,
            'theme' => Select2::THEME_CLASSIC,
            'options' => ['placeholder' => 'Select a state ...', 'autocomplete' => 'off'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]);
        ?>
    </div>
    <div class="col-sm-6">
       <label>Theme CLASSIC (Multiple)</label>
        <?php
        echo Select2::widget([
            'name' => 'kv_theme_classic_2',
            'data' => $data,
            'theme' => Select2::THEME_CLASSIC,
            'options' => ['placeholder' => 'Select a state ...', 'multiple' => true, 'autocomplete' => 'off'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]);
        ?>
    </div>
</div>
<br>
<div class="row">
    <div class="col-sm-6">
       <label>Theme DEFAULT (Single)</label>
        <?php
        echo Select2::widget([
            'name' => 'kv_theme_default_1',
            'data' => $data,
            'theme' => Select2::THEME_DEFAULT,
            'options' => ['placeholder' => 'Select a state ...', 'autocomplete' => 'off'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]);
        ?>
    </div>
    <div class="col-sm-6">
       <label>Theme DEFAULT (Multiple)</label>
        <?php
        echo Select2::widget([
            'name' => 'kv_theme_default_2',
            'data' => $data,
            'theme' => Select2::THEME_DEFAULT,
            'options' => ['placeholder' => 'Select a state ...', 'multiple' => true, 'autocomplete' => 'off'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]);
        ?>
    </div>
</div>
Bootstrap v5.x Only Usage of Select2 with Bootstrap 5.x floating labels. To use this feature you can either use it with kartik\form\ActiveForm widget with ActiveForm::type set to ActiveForm::TYPE_FLOATING. Alternatively, you can directly embed the input widget in a div with CSS class form-floating as shown below. Note that the floating labels styling will not vary with the Select2 size modifiers and hence will not be dependent on the Select2 size property.
 

Bootstrap 5 Floating Labels (Single Select).


 

Bootstrap 5 Floating Labels (Multiple Select)


 

Bootstrap 5 Floating Labels (Single Select RTL)


 

Bootstrap 5 Floating Labels (Multiple Select RTL)

<div class="row">
    <div class="col-sm-6">
        <div class="form-floating">
            <?php
            echo Select2::widget([
                'name' => 'float_state_01',
                'data' => $data,
                'options' => ['placeholder' => 'Select a state...'],
                'pluginOptions' => ['allowClear' => true],
            ]);
            ?>
            <label class="form-label">State</label>
        </div>
    </div>
    <div class="col-sm-6">
        <div class="alert alert-info"><p>Bootstrap 5 Floating Labels (Single Select).</p></div>
    </div>
</div>
<hr class="kv-hr">
<div class="row">
    <div class="col-sm-6">
        <div class="form-floating">
            <?php
            echo Select2::widget([
                'name' => 'float_state_02',
                'data' => $data,
                'options' => ['placeholder' => 'Select a state...', 'multiple' => true],
                'pluginOptions' => ['allowClear' => true],
            ]);
            ?>
            <label class="form-label">State</label>
        </div>
    </div>
    <div class="col-sm-6">
        <div class="alert alert-info"><p>Bootstrap 5 Floating Labels (Multiple Select)</p></div>
    </div>
</div>
<div class="row">
    <div class="col-sm-6">
        <div class="form-floating">
            <?php
            echo Select2::widget([
                'name' => 'float_state_03',
                'data' => $data,
                'options' => ['dir' => 'rtl', 'placeholder' => 'Select a state...'],
                'pluginOptions' => ['allowClear' => true],
            ]);
            ?>
            <label class="form-label">State</label>
        </div>
    </div>
    <div class="col-sm-6">
        <div class="alert alert-info"><p>Bootstrap 5 Floating Labels (Single Select RTL)</p></div>
    </div>
</div>
<hr class="kv-hr">
<div class="row">
    <div class="col-sm-6">
        <div class="form-floating">
            <?php
            echo Select2::widget([
                'name' => 'float_state_04',
                'data' => $data,
                'options' => ['dir' => 'rtl', 'placeholder' => 'Select a state...', 'multiple' => true],
                'pluginOptions' => ['allowClear' => true],
            ]);
            ?>
            <label class="form-label">State</label>
        </div>
    </div>
    <div class="col-sm-6">
        <div class="alert alert-info"><p>Bootstrap 5 Floating Labels (Multiple Select RTL)</p></div>
    </div>
</div>
An example demonstrating the various sizes of Select 2 widget with orientation for right to left languages.

Single Select

 
 
 

Multi Select

 
 
 

Single Select (RTL)

 
 
 

Multi Select (RTL + Addon)

 
 
 
use kartik\select2\Select2;
// Various Select2 Sizes
echo Select2::widget([
    'name' => 'kv-state-200',
    'data' => $data,
    'size' => Select2::SMALL,
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]) .
Select2::widget([
    'name' => 'kv-state-210',
    'data' => $data,
    'size' => Select2::MEDIUM,
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]) .
Select2::widget([
    'name' => 'kv-state-220',
    'data' => $data,
    'size' => Select2::LARGE,
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]) .
Select2::widget([
    'name' => 'kv-state-230',
    'data' => $data,
    'size' => Select2::SMALL,
    'options' => ['placeholder' => 'Select a state ...', 'multiple' => true],
    'pluginOptions' => [
        'allowClear' => true
    ],
]) .
Select2::widget([
    'name' => 'kv-state-240',
    'data' => $data,
    'size' => Select2::MEDIUM,
    'options' => ['placeholder' => 'Select a state ...', 'multiple' => true],
    'pluginOptions' => [
        'allowClear' => true
    ],
]) .
Select2::widget([
    'name' => 'kv-state-250',
    'data' => $data,
    'size' => Select2::LARGE,
    'options' => ['placeholder' => 'Select a state ...', 'multiple' => true],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);
$addon = [
    'prepend' => [
        'content' => '<i class="fas fa-globe"></i>'
    ],
    'append' => [
        'content' => Html::button('<i class="fas fa-map-marker-alt"></i>', [
                'class' => 'btn btn-primary',
                'title' => 'Mark on map',
                'data-toggle' => 'tooltip'
            ]),
        'asButton' => true
    ]
];
// FOR RTL orientation with addon, set 'options' => ['dir' => 'rtl'] in all of the above
// and set addon property to $addon
Tagging support for Select2 widget including ability to add one's own tags. This typically is effective with options['multiple'] set to true. However, you can use it for single tagging as well. You must write your own server/ajax code for saving these added values and/or refreshing the select2 via javascript or page refresh.
 

Tagging support (Multiple). Allow automatic tokenization and add choices automatically as the user is typing into the search field. Try typing in the search field and entering a space or a comma set as tokenSeparators.


 

Tagging support (Multiple) that maintains the order of selected tags by setting the maintainOrder property to true.


 

Tagging support (Multiple) for an update scenario that maintains the order of selected tags on initialization when the maintainOrder property is set to true.


 

Advanced toggle all configuration and styling for multiple selection. Configure the toggle all button label and styles for select and unselect.


 

Tagging support for a single select. Allow automatic tokenization and add choices automatically as the user is typing into the search field. You can create option values even for a single select on the fly in the search box. However, you must write your own server/ajax code for saving these added values and/or refreshing the select2 via javascript or page refresh.

use kartik\select2\Select2;
$data = [
    "red" => "red",
    "green" => "green",
    "blue" => "blue",
    "orange" => "orange",
    "white" => "white",
    "black" => "black",
    "purple" => "purple",
    "cyan" => "cyan",
    "teal" => "teal"
];

// Tagging support Multiple
$model->colorTags =  ['red', 'green']; // initial value
echo $form->field($model, 'colorTags')->widget(Select2::classname(), [
    'data' => $data,
    'options' => ['placeholder' => 'Select a color ...', 'multiple' => true],
    'pluginOptions' => [
        'tags' => true,
        'tokenSeparators' => [',', ' '],
        'maximumInputLength' => 10
    ],
])->label('Tag Multiple');

// Tagging support Multiple (maintain the order of selection)
echo '<label class="control-label">Tag Multiple</label>';
echo Select2::widget([
    'name' => 'color_2',
    'value' => ['red', 'green'], // initial value
    'data' => $data,
    'maintainOrder' => true,
    'options' => ['placeholder' => 'Select a color ...', 'multiple' => true],
    'pluginOptions' => [
        'tags' => true,
        'maximumInputLength' => 10
    ],
]);

// Tagging support (Multiple) for an update scenario that maintains the order of 
// selected tags on initialization when the (maintain the order of selection)
echo '<label class="control-label">Tag Multiple</label>';
echo Select2::widget([
    'name' => 'color_2a',
    'value' => ['teal', 'green', 'red'], // initial value (will be ordered accordingly and pushed to the top)
    'data' => $data,
    'maintainOrder' => true,
    'options' => ['placeholder' => 'Select a color ...', 'multiple' => true],
    'pluginOptions' => [
        'tags' => true,
        'maximumInputLength' => 10
    ],
]);

// Tagging support Multiple (maintain the order of selection)
echo '<label class="control-label">Tag Multiple</label>';
echo Select2::widget([
    'name' => 'color_3',
    'value' => ['red', 'green'], // initial value
    'data' => $data,
    'maintainOrder' => true,
    'toggleAllSettings' => [
        'selectLabel' => '<i class="fas fa-check-circle"></i> Tag All',
        'unselectLabel' => '<i class="fas fa-times-circle"></i> Untag All',
        'selectOptions' => ['class' => 'text-success'],
        'unselectOptions' => ['class' => 'text-danger'],
    ],
    'options' => ['placeholder' => 'Select a color ...', 'multiple' => true],
    'pluginOptions' => [
        'tags' => true,
        'maximumInputLength' => 10
    ],
]);

// Tagging support Single
echo '<label class="control-label">Tag Single</label>';
echo Select2::widget([
    'name' => 'color_3',
    'value' => 'red', // initial value
    'data' => $data,
    'options' => ['placeholder' => 'Select a color ...'],
    'pluginOptions' => [
        'tags' => true,
        'tokenSeparators' => [',', ' '],
        'maximumInputLength' => 10
    ],
]);
An example demonstrating the use of Select2 loaded with a remote ajax action querying a large number of records.
 

Fetching and querying large data using ajax. For example type cal. This is a multiple select example with an initial value (which you can set via data property as key value pairs).

/*******
 * View
 ******/

// The controller action that will render the list
$url = \yii\helpers\Url::to(['city-list']);

// The widget
use kartik\select2\Select2; // or kartik\select2\Select2
use yii\web\JsExpression;
use yii\helpers\ArrayHelper;
use common\models\City;

// Get the initial saved city data (note $model->city is an array of city ids)
$dataList = City::find()->andWhere(['id' => $model->city])->all();
$data = ArrayHelper::map($dataList, 'id', 'name');

echo $form->field($model, 'city')->widget(Select2::classname(), [
    'data' => $data,
    'options' => ['multiple'=>true, 'placeholder' => 'Search for a city ...'],
    'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength' => 3,
        'language' => [
            'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
        ],
        'ajax' => [
            'url' => $url,
            'dataType' => 'json',
            'data' => new JsExpression('function(params) { return {q:params.term}; }')
        ],
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('function(city) { return city.text; }'),
        'templateSelection' => new JsExpression('function (city) { return city.text; }'),
    ],
]);

/*************
 * Controller
 ************/
public function actionCityList($q = null, $id = null) {
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = ['results' => ['id' => '', 'text' => '']];
    if (!is_null($q)) {
        $query = new Query;
        $query->select('id, name AS text')
            ->from('city')
            ->where(['like', 'name', $q])
            ->limit(20);
        $command = $query->createCommand();
        $data = $command->queryAll();
        $out['results'] = array_values($data);
    }
    elseif ($id > 0) {
        $out['results'] = ['id' => $id, 'text' => City::find($id)->name];
    }
    return $out;
}
An advanced example that combines AJAX based loading, querying a remote repository, and templating to display formatted results.
 

Querying a remote repository via AJAX with output results formatted via templates. The initial value display text can be set via initValueText. This example also includes pagination of results and infinite scrolling of displayed results. You can search for example yii2-grid OR yii2-widgets.

$formatJs = <<< 'JS'
var formatRepo = function (repo) {
    if (repo.loading) {
        return repo.text;
    }
    var markup =
'<div class="row">' + 
    '<div class="col-sm-5">' +
        '<img src="' + repo.owner.avatar_url + '" class="img-rounded" style="width:30px" />' +
        '<b style="margin-left:5px">' + repo.full_name + '</b>' + 
    '</div>' +
    '<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
    '<div class="col-sm-3"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
'</div>';
    if (repo.description) {
      markup += '<p>' + repo.description + '</p>';
    }
    return '<div style="overflow:hidden;">' + markup + '</div>';
};
var formatRepoSelection = function (repo) {
    return repo.full_name || repo.text;
}
JS;

// Register the formatting script
$this->registerJs($formatJs, View::POS_HEAD);

// script to parse the results into the format expected by Select2
$resultsJs = <<< JS
function (data, params) {
    params.page = params.page || 1;
    return {
        results: data.items,
        pagination: {
            more: (params.page * 30) < data.total_count
        }
    };
}
JS;
// render your widget
echo Select2::widget([
    'name' => 'kv-repo-template',
    'value' => '14719648',
    'initValueText' => 'kartik-v/yii2-widgets',
    'options' => ['placeholder' => 'Search for a repo ...'],
    'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength' => 1,
        'ajax' => [
            'url' => "https://api.github.com/search/repositories",
            'dataType' => 'json',
            'delay' => 250,
            'data' => new JsExpression('function(params) { return {q:params.term, page: params.page}; }'),
            'processResults' => new JsExpression($resultsJs),
            'cache' => true
        ],
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('formatRepo'),
        'templateSelection' => new JsExpression('formatRepoSelection'),
    ],
]);
An example demonstrating the use of input group addons with Select2. You can prepend or append addons or use both as seen in the example.
 
use kartik\select2\Select2;
use kartik\helpers\Html;

echo Select2::widget([
    'name' => 'state_200',
    'data' => $us_states,
    'size' => Select2::MEDIUM,
    'addon' => [
        'prepend' => [
            'content' => '<i class="fas fa-globe"></i>'
        ],
        'append' => [
            'content' => Html::button('<i class="fas fa-map-marker-alt"></i>', [
                'class' => 'btn btn-primary', 
                'title' => 'Mark on map', 
                'data-toggle' => 'tooltip'
            ]),
            'asButton' => true
        ]
    ]
]);

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