conquer/select2

Yii2 Select2 小部件

安装次数: 58,743

依赖: 4

建议者: 0

安全: 0

星标: 16

关注者: 5

分支: 6

公开问题: 0

类型:yii2-extension

1.5.4-beta 2017-01-10 19:21 UTC

README

描述

Select2 为您提供可定制的搜索选择框,支持搜索、标记、远程数据集、无限滚动和其他许多常用选项。更多详情请访问 Select2

安装

安装此扩展的首选方式是通过 composer

安装时,可以运行

$ php composer.phar require conquer/select2 "*"

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

"conquer/select2": "*"

使用方法

基本使用

// Form edit view
use conquer\select2\Select2Widget;
use yii\helpers\ArrayHelper;

$form->field($model, 'attribute')->widget(
    Select2Widget::className(),
    [
        'items'=>ArrayHelper::map(Catalog::find()->all(), 'id', 'name')
    ]
);

Ajax

use conquer\select2\Select2Action;
...

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'ajax' => [
                'class' => Select2Action::className(),
                'dataCallback' => [$this, 'dataCallback'],
            ],
        ];
    }
    /**
     * 
     * @param string $q
     * @return array
     */
    public function dataCallback($q)
    {
        $query = new ActiveQuery(Catalog::className());
        return [
            'results' =>  $query->select([
                    'catalog_id as id',
                    'catalog_name as text', 
                ])
                ->filterWhere(['like', 'catalog_name', $q])
                ->asArray()
                ->limit(20)
                ->all(),
        ];
    }
}

// Form edit view:

$form->field($model, 'attribute')->widget(
    Select2Widget::className(),
    [
        'ajax' => ['site/ajax']
    ]
);

Jquery 事件

列出 Select2 JQuery 事件。你必须以 event-name => event-function 的格式定义事件。所有事件将按顺序堆叠。请参考 插件选项文档 获取详细信息。

例如

$form->field($model, 'attribute')->widget(
    Select2Widget::className(),
    [
        'events' => [
            'select2:open' => "function() { log('open'); }",
        ]
    ]
);

使用 Ajax 和自定义模板初始化多选。

<?= $form->field($model, 'multipleItems')->widget(Select2Widget::className(), [
    'options' => [
        'placeholder' => 'Select items ...',
    ],
    'ajax' => Url::to(['items/search']),
    'multiple' => true,
    'items' => ArrayHelper::map($model->multipleItems, 'id', 'text'),
    // Initial data the same, as returned results from Ajax request items/search
    'data' => $model->multipleItems,
    'settings' => [
        'ajax' => ['delay' => 250],
        'minimumInputLength' => 1,
        'minimumResultsForSearch' => -1,
        /** 
         * Handlebars here is used as example of using template engine
         * If you will not provide initial data,
         *   custom templates will not access additional info of items
         */
        'templateResult' => 'js:Handlebars.compile($("#template-result").html())',
        'templateSelection' => 'js:Handlebars.compile($("#template-selection").html())',
        'escapeMarkup' => 'js:function(markup){ return markup; }',
    ],
]) ?>

许可证

conquer/select2 在 MIT 许可证下发布。有关详细信息,请参阅捆绑的 LICENSE 文件。