yii2-selectivity

Usage

Select a single city

<?php

/* @var $cities array */
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\modules\yii2extensions\models\SelectivityForm */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use wbraganca\selectivity\SelectivityWidget;
?>

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'city')->label(false)->widget(SelectivityWidget::classname(), [
    'pluginOptions' => [
        'allowClear' => true,
        'items' => $cities,
        'placeholder' => 'No city selected'
    ]
]) ?>

<?php ActiveForm::end(); ?>

Select multiple cities

<?php

/* @var $cities array */
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\modules\yii2extensions\models\SelectivityForm */

use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\JsExpression;
use yii\bootstrap\ActiveForm;
use wbraganca\selectivity\SelectivityWidget;

// init values
$model->cities = [2,15];

$selectivityValues = [];
foreach ($model->cities as $id) {
    $selectivityValues[] = ['id' => $id, 'text' => $cities[$id]];
}
?>

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'cities')->label(false)->widget(SelectivityWidget::classname(), [
    'pluginOptions' => [
        'value' => $model->cities,
        'items' => $cities,
        'multiple' => true,
        'placeholder' => 'Type to search a city',
        'initSelection' => new JsExpression('function(data, callback) {
            $("#' . Html::getInputId($model, 'cities') . '").selectivity("data", ' . Json::encode($selectivityValues) . ')
        }')
    ]
]) ?>

<?php ActiveForm::end(); ?>

For more options, visit: https://arendjr.github.io/selectivity/#api