Search by

Select2 widgets for Yii2 with ActiveForm, AJAX searches, and native browser assets.

0.2.2 2026-12-02 10:44 UTC

This package is auto-updated.

Last update: 2026-12-02 10:49:48 UTC


README

Yii Framework

Select2


PHPUnit Coverage Mutation Testing PHPStan

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.

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-select2 skill: Select2 widget installation with Foxy assets, ActiveForm validation of selections and tags, remote data, events, themes and repeatable lifecycle cleanup.
  • ๐Ÿงญ yii2-framework skill: 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

PHP Yii 2.0.55+ Yii 22.0.x Latest Stable Version Total Downloads

Project status

PHPStan Level Max Quality ECS

Security

OpenSSF Scorecard Zizmor

Built with AI

Built with Claude Code Built with Codex Reviewed by CodeRabbit

Our social networks

Follow on X Follow on Facebook Join our Subreddit Join on Telegram

Credits

Original project: yii-cms/yii2-select2 by the Yii CMS contributors.

License

License