khotim / yii2-select2
Yii 框架的 Select2 扩展
v1.0
2016-03-02 11:07 UTC
Requires
- php: >=5.4.0
- yiisoft/yii2: *
This package is not auto-updated.
Last update: 2024-09-14 17:32:11 UTC
README
Yii2 Select2 是一个从 \yii\widgets\inputWidget
继承的输入小部件,它使用了 Select2 插件 的功能。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令之一
php composer.phar require --prefer-dist khotim/yii2-select2 "*"
或者
"khotim/yii2-select2": "*"
将以下内容添加到您的 composer.json
文件的 require 部分中。
用法
此扩展与 Html::dropDownList()
类似,但它使用一个文本输入来从数据源搜索可用的选项列表。使用预定义数组的最低用法如下:
echo \khotim\select2\Select2::widget([ 'name' => 'option_list', 'data' => [ 0 => 'enhancement', 1 => 'bug', 2 => 'duplicate', 3 => 'invalid', 4 => 'wontfix' ], ]);
您还可以通过配置其 widget()
方法将此扩展附加到 ActiveField,如下所示
<?= $form->field($model, 'option_list')->widget(\khotim\select2\Select2::className(), [ 'data' => [ 0 => 'enhancement', 1 => 'bug', 2 => 'duplicate', 3 => 'invalid', 4 => 'wontfix' ], ]) ?>
使用通过 AJAX 调用数据源的示例用法
视图
<?= $form->field($model, 'option_list')->widget(\khotim\select2\Select2::className(), [ 'clientOptions' => [ 'escapeMarkup' => new \yii\web\JsExpression('function (markup) { return markup; }'), 'minimumInputLength' => 1, 'placeholder' => 'search option list...', 'allowClear' => true, 'ajax' => [ 'url' => \yii\helpers\Url::to(['lookup/search-option']), 'dataType' => 'json', 'delay' => 250, 'data' => new \yii\web\JsExpression('function (params) { return { q: params.term, // search term page: params.page }; }'), 'processResults' => new \yii\web\JsExpression('function (data, params) { // parse the results into the format expected by Select2 // since we are using custom formatting functions we do not need to // alter the remote JSON data, except to indicate that infinite // scrolling can be used params.page = params.page || 1; return { results: data.items, pagination: { more: (params.page * 30) < data.total_count } }; }'), 'cache' => true ] ] ])?>
控制器
public function actionSearchOption() { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $param = Yii::$app->request->get('q'); $models = \app\models\OptionSearch::findAll($param); $data['items'] = \yii\helpers\ArrayHelper::toArray($models, [ 'app\models\OptionSearch' => [ 'id', 'text' => function ($model) { return $model->name; } ] ]); return $data; }