yii2-extensions / select2
Select2 widgets for Yii2 with ActiveForm, AJAX searches, and native browser assets.
Requires
- php: >=8.3
- php-forge/foxy: ^0.4
- yiisoft/yii2: ~2.0.55 || ^22.0@dev
Requires (Dev)
- maglnet/composer-require-checker: ^4.7
- php-forge/support: ^0.1
- phpunit/phpunit: ^10.5
- roave/infection-static-analysis-plugin: ^1.34
- symplify/easy-coding-standard: ^13.3
- yii2-extensions/phpstan: ^0.6
Suggests
- yii2-extensions/bootstrap6: Bootstrap 6 forms and asset bundles for the `bootstrap-6` Select2 theme.
- yiisoft/yii2-bootstrap5: Bootstrap 5 forms and assets for the `bootstrap-5` Select2 theme.
- yiisoft/yii2-jquery: Required on Yii 22 for ActiveForm client validation; bootstrap yii\jquery\Bootstrap.
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-02 10:49:48 UTC
README
Select2
Searchable Select2 widgets for Yii2 forms
ActiveForm integration, multiple selections, tagging, and paginated AJAX searches
Quick start
Installation
Configure Foxy native and the asset aliases in the installation guide, then install:
composer require --prefer-dist --prefer-stable php-forge/foxy:^0.4 yii2-extensions/select2:^0.2
Usage
A shipment form: country comes from a fixed list, city is searched remotely in a City ActiveRecord with id and
name, and tags accepts free text.
use yii\base\Model; final class ShipmentForm extends Model { public $country = ''; public $city = ''; public $tags = []; public function rules(): array { return [ // Clearing a multiple select posts '' through Yii's hidden input, not an empty array. [ 'tags', 'filter', 'filter' => static fn ($value) => $value === '' ? [] : $value, ], [ ['country', 'city'], 'required', ], [ 'country', 'in', 'range' => ['mx', 'ca'], ], // A posted ID is user input, whatever the search endpoint returned: check it against the table. [ 'city', 'exist', 'targetClass' => City::class, 'targetAttribute' => 'id', ], // Tags are free text, so every tag is validated. By default an empty tag, or a missing value in place of // the array, would skip the rule; `skipOnEmpty` is disabled at both levels. [ 'tags', 'each', 'rule' => ['string', 'min' => 1, 'max' => 30, 'skipOnEmpty' => false], 'skipOnEmpty' => false, ], ]; } }
In a view with $form and $model:
use yii\helpers\Url; use yii\web\JsExpression; use Yii2\Extensions\Select2\Select2; // ActiveForm supplies the label, the error node and the validation classes; the widget adds no class of its own. echo $form ->field($model, 'country') ->widget( Select2::class, [ 'items' => [ 'mx' => 'Mexico', 'ca' => 'Canada', ], // The placeholder and the clear button need an empty option; `prompt` renders it. 'options' => ['prompt' => ''], 'clientOptions' => [ 'placeholder' => 'Choose a country', 'allowClear' => true, ], ], ); // Remote search. Only the current city is rendered, when one is selected and valid: AJAX cannot recover the label // of a stored ID. $city = $model->city === null || $model->city === '' || $model->hasErrors('city') ? [] : City::find() ->select('name') ->where(['id' => $model->city]) ->indexBy('id') ->column(); echo $form ->field($model, 'city') ->widget( Select2::class, [ 'items' => $city, 'options' => ['prompt' => ''], 'clientOptions' => [ 'placeholder' => 'Search cities', 'minimumInputLength' => 1, 'ajax' => [ 'url' => Url::to(['city/search']), 'dataType' => 'json', 'delay' => 250, // A function-valued option needs JsExpression; a plain string stays a string. 'data' => new JsExpression( 'function (params) { return {q: params.term || "", page: params.page || 1}; }', ), ], ], // Handlers run on the original select and are bound once, even when the widget is initialized again. 'clientEvents' => ['select2:select' => 'function (event) { console.log(event.params.data.id); }'], ], ); // `multiple` posts an array and `tags` lets the user add values. Only tags that passed validation are redisplayed, // as options and as the selection, so a malformed submission never reaches the renderer. $tags = $model->hasErrors('tags') ? [] : $model->tags; echo $form ->field($model, 'tags') ->widget( Select2::class, [ 'items' => array_combine($tags, $tags), 'options' => [ 'multiple' => true, 'value' => $tags, ], 'clientOptions' => [ 'tags' => true, 'maximumSelectionLength' => 5, ], ], );
Each widget initializes through the yiiSelect2 jQuery plugin, which also mirrors labels, hints and aria-invalid on
the visible selection. Clean up before replacing a Pjax fragment or removing a field:
// Removes the Select2 instance, the handlers bound by the widget and its attribute observer. jQuery(document.getElementById("shipmentform-city")).yiiSelect2("destroy");
The AJAX guide has the
search endpoint and its JSON shape. The
Configuration Guide covers standalone
widgets, manual initialization and focus on invalid fields, and the
Installation Guide the optional
bootstrap-5 and bootstrap-6 themes.
The widget uses Select2 4.0 and requires jQuery. Foxy installs published assets without a Node.js build. See the installation guide for the Yii 22 client-validation adapter and frontend compatibility.
Documentation
Practical guides and usage examples for Select2 widgets, forms, and remote searches.
- ๐ Installation Guide: native assets and optional Bootstrap 5 and 6 themes.
- โ๏ธ Configuration Guide: models, ActiveForm, accessibility, events, and lifecycle.
- ๐ก Usage Examples
- ๐ Upgrade Guide
- ๐งช Testing Guide
- ๐ AJAX Searches and Pagination
The guides and the API reference generated from
the PHPDoc in src/ are published at https://yii2-framework.github.io/docs/extensions/select2/.
AI assistance
AI agents: read the documentation index and fetch the Markdown version
of a page by appending index.md to its URL. The
AI agents guide covers skill installation, client setup and
verification.
- ๐ค
yii2-select2skill: Select2 widget installation with Foxy assets, ActiveForm validation of selections and tags, remote data, events, themes and repeatable lifecycle cleanup. - ๐งญ
yii2-frameworkskill: Yii 22.0 application conventions.
The hosted documentation covers Yii 22.0. If it does not match the installed revision or is unavailable, use the repository guides, the skill source, the source PHPDoc and the changelog.
Package information
Project status
Security
Built with AI
Our social networks
Credits
Original project: yii-cms/yii2-select2 by the Yii CMS contributors.