platx / yii2-relative-select2

基于 Yii2 框架的相对 Select2 小部件

安装: 124

依赖项: 0

建议者: 0

安全性: 0

星标: 0

关注者: 1

分支: 1

开放问题: 0

类型:yii2-extension

dev-master 2016-01-28 11:22 UTC

This package is not auto-updated.

Last update: 2020-10-02 21:15:15 UTC


README

基于 Yii2 框架的相对 Select2 小部件。它允许通过 AJAX 动态获取数据,依赖于父级属性。小部件扩展并需要 kartik-v Select2 小部件(https://github.com/kartik-v/yii2-widget-select2)。

安装

推荐通过 composer 安装此扩展。

运行以下命令之一:

php composer.phar require --prefer-dist platx/yii2-relative-select2 "*"

或添加以下内容到您的 composer.json 文件的 require 部分。

"platx/yii2-relative-select2": "*"

使用方法

与 ActiveForm 和模型一起使用

<?= \$form->field($model, 'state_1')->widget(\platx\relativeselect2\RelativeSelect2::classname(), [
     'parentName' => 'parent_attribute_name',
     'url' => Url::to(['/ajax/list-items']),
     'options' => ['placeholder' => 'Select a state ...'],
     'pluginOptions' => [
         'allowClear' => true
     ],
]) ?>

带有模型且不使用 ActiveForm

<?= \platx\relativeselect2\RelativeSelect2::widget([
     'model' => $model,
     'attribute' => 'state_2',
     'parentName' => 'parent_attribute_name',
     'url' => Url::to(['/ajax/list-items']),
     'options' => ['placeholder' => 'Select a state ...'],
     'pluginOptions' => [
         'allowClear' => true
     ],
]) ?>

不使用模型并实现多选

<?= \platx\relativeselect2\RelativeSelect2::widget([
     'name' => 'state_2',
     'parentName' => 'parent_attribute_name',
     'url' => Url::to(['/ajax/list-items']),
     'options' => ['placeholder' => 'Select a state ...'],
     'pluginOptions' => [
         'allowClear' => true,
         'multiple' => true
     ],
]) ?>

数据获取的控制器示例

<?php
class AjaxController extends \yii\web\Controller
{
    public function actionListItems($query = null)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!is_null($query)) {
            $models = Model::find()
                ->andWhere(['parent_id' => $query])
                ->all();
            $items = [];
            foreach($models as $model) {
                $items[] = ['id' => $model->id, 'text' => $model->name];
            }
            if(!empty($items)) {
                $out['results'] = $items;
            }
        }
        return $out;
    }
}