Giter Site home page Giter Site logo

kartik-v / yii2-widget-select2 Goto Github PK

View Code? Open in Web Editor NEW
323.0 19.0 145.0 638 KB

Enhanced Yii2 wrapper for the Select2 jQuery plugin (sub repo split from yii2-widgets).

Home Page: http://demos.krajee.com/widget-details/select2

License: Other

CSS 63.64% JavaScript 4.27% PHP 32.09%

yii2-widget-select2's Introduction

Krajee Logo
yii2-widget-select2
Donate       kartikv

Financial Contributors on Open Collective Stable Version Unstable Version License

Total Downloads Monthly Downloads Daily Downloads

This is the Select2 widget and a Yii 2 enhanced wrapper for the Select2 jQuery plugin. This input widget is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results. The widget is specially styled for Bootstrap 3 and offers a few enhancements not available in the source plugin. The widget allows graceful degradation to a normal HTML select or text input, if the browser does not support JQuery.

NOTE: This extension is a sub repo split of yii2-widgets. The split has been done since 08-Nov-2014 to allow developers to install this specific widget in isolation if needed. One can also use the extension the previous way with the whole suite of yii2-widgets.

Installation

The preferred way to install this extension is through composer. Check the composer.json for this extension's requirements and dependencies. Read this web tip /wiki on setting the minimum-stability settings for your application's composer.json.

To install, either run

$ php composer.phar require kartik-v/yii2-widget-select2 "@dev"

or add

"kartik-v/yii2-widget-select2": "@dev"

to the require section of your composer.json file.

Release Changes

NOTE: Refer the CHANGE LOG for details on changes to various releases.

The widget has a major version revamp with v2.0. This release includes updates to use Select2 plugin release v4.0. Select2 release v4.0 is a major rewrite over Select2 v3.x and hence quite a few enhancements or changes should be expected. To use the earlier plugin release v3.5.2, you must point it to the v1.0.1 release of the widget.

Enhancements with release v2.0:

  • New theme property that allows you to set themes in Select2 to style your widget.
  • A brand new theme by Krajee Select2::THEME_KRAJEE is specially styled for Select2. This will help achieve various new yii2-widget-select2 features. This theme matches the bootstrap 3 styling with enhancements.
  • Additional themes provided in form of Select2::THEME_DEFAULT, Select2::THEME_CLASSIC, and Select2::THEME_BOOTSTRAP. One can add their own custom theme and configure the widget.
  • No more query plugin property needed. It is also not mandatory to configure data even if you have not set tags or query or ajax. Widget will intelligently evaluate the properties and default list values.
  • Enhanced tagging support. Use it just like a multiple select but with taggable values. In addition, one can create tags on the fly.
  • Enhanced ajax support. Refer the demos for details.
  • The initSelection method of Select2 3.5.x plugin is obsolete/removed. New initValueText property is been provided with the Select2 widget to cater to this (e.g. for ajax based loading).
  • Ability to disable selective option values in the Select2 dropdown OR add HTML attributes to selective options.
  • Enhancement by Krajee to disable the search box to use like a normal select.
  • Enhancements to locales and translations. Allow multiple language Select2 widgets on the same page.

Documentation and Demo

You can refer detailed documentation and demos and API Code Documentation on usage of the extension.

Usage

use kartik\select2\Select2;

// Normal select with ActiveForm & model
echo $form->field($model, 'state_1')->widget(Select2::classname(), [
    'data' => $data,
    'language' => 'de',
    'options' => ['placeholder' => 'Select a state ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);

// Multiple select without model
echo Select2::widget([
    'name' => 'state_2',
    'value' => '',
    'data' => $data,
    'options' => ['multiple' => true, 'placeholder' => 'Select states ...']
]);

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

License

yii2-widget-select2 is released under the BSD-3-Clause License. See the bundled LICENSE.md for details.

yii2-widget-select2's People

Contributors

amin3mej avatar boliver20 avatar dersonsena avatar digitv avatar dmitry-kulikov avatar dogrocker avatar drmagice avatar edofre avatar giannisdag avatar iamguba avatar joshuatam avatar kartik-v avatar ktropp avatar kullarkert avatar linkaixiang4883 avatar maxxer avatar mfaeezmazlan avatar nazakar avatar niki7har avatar nikosid avatar nurielmeni avatar pigochu avatar rangelreale avatar romeromsk avatar shaposhnikov avatar skeeks-semenov avatar syedmuneer avatar vishub avatar wilberto-dzul avatar wodelrock avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-widget-select2's Issues

500 error while ajax timeout

Because ajax call timeout, I set the timeout to 30s. Although the json result returns correctly , but still 500 error happens, and the json result can not be rendered

    'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength' => 2,
        'ajax' => [
            'timeout' => 30000,
            'url' => Url::to([
                'fields/ajaxfields', 'pid'=>$model->pid
            ]),
            'dataType' => 'json',
            'data' => new JsExpression('function(params) { return {q:params.term}; }'),
            'cache' => true
        ],
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('formatRepo'),
        'templateSelection' => new JsExpression('formatRepoSelection')
    ]

this widget have event select2-select or select?

this widget have event select2-select or select or something after select?
I used
'pluginEvents' => [
"select"=>"function() {console.log('select'); }",
"select2-select" => "function() { console.log('select2-select'); }",
]
but nothing show in log

array_combine() expects parameter 1 to be array, string given

Hi
Before this commit it was working.

The error message : "array_combine() expects parameter 1 to be array, string given".
The file : kartik-v\yii2-widget-select2\Select2.php at line 133

My code :

//$data = 'keyword1,keyword2,keyword3'
$form->field($model, 'keywords')->widget(Select2::className(), [
    'pluginOptions' => [
        'tags' => true,
    ],
    'options' => [
        'multiple' => true
    ]
])

$model->keywords contains a string, not an array.
And the input is not filled anymore with the values.

Thanks

order

it's my code

<?= $form->field($model, 'filters')->widget(Select2::classname(), [
        'data' => array_merge(["" => ""],['Filter 1'=>'Filter 1','Filter 2'=>'Filter 2','Filter 3'=>'Filter 3']),
        'options' => ['multiple' => true,'placeholder' => 'Select a filter ...'],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
    ?>    

what i do

filters

then i get

filters1

how i can save the order of filters?

filters2

Multiple + Array entity + Ajax problem

Got error "Array to string conversion" from Yii2 framework when using like so:

            <?= $form->field($model, 'hints')->widget(SelectAjaxWrapper::className(), [
                'url' => Url::to(['entity-selector/hints']),
                'placeholder' => 'Выберите подсказку ...',
                'options' => [
                    'multiple' => true
                ],
            ]); ?>

I have wrapped this widget:

class SelectAjaxWrapper extends Select2
{
    public $url;
    public $placeholder;

    public function init()
    {

        $this->pluginOptions['minimumInputLength'] = 3;
        $this->pluginOptions['allowClear'] = true;
        $this->pluginOptions['ajax']['url'] = $this->url;
        $this->pluginOptions['ajax']['dataType'] = 'json';
        $this->pluginOptions['ajax']['data'] = new JsExpression('function(term,page){return{search:term};}');
        $this->pluginOptions['ajax']['results'] = new JsExpression('function(data,page){return{results:data.results};}');
        $this->pluginOptions['initSelection'] = new JsExpression('function (element, callback) {
    var id = $(element).val();
    if (id !== "") {
        $.ajax("{$this->url}?id=" + id, {
            dataType: "json"
        }).done(function (data) {
            callback(data.results);
        });
    }
}');
        $this->options['placeholder'] = $this->placeholder;
        parent::init();
    }
}

It's working when I using simple data array and no ajax.
Please help :)

Showing as a dropDownList

Showing as a dropdownlist only, no search options there,

<?php echo $form->field($model, 'category_id')->widget(Select2::classname(), [
            'language' => 'en',
            'data' => ArrayHelper::map(CourseCategories::find()->all(),'category_id','name'),
            'options' => ['placeholder' => 'Plsease Select a Category'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]);
        ?>

Kartik GridView with ExpandRowColumn select2 attribute disappears on detail page

there's something wrong on a \kartik\widgets\Select2 widget used into an ExpandRowColumn detail page:

detail page

Expanding the row to show the detail page, it will show only the first select2 attribute.

The view:

'idAssicurato' => [
    'type'=>Form::INPUT_WIDGET,
    'label' => "Assicurato",
    'widgetClass'=>'\kartik\widgets\Select2', 
    'options'=>['data' => ArrayHelper::map(Assicurato::find()->all(), 'id', 'nomeAssicurato')]
]

If I use 'type'=>Form::INPUT_WIDGET it works.
Maybe a bug?

Alex

Just curious tagging for single not multiple

Hi,

I was wondering whether it is possible to use tagging for single selection and not multiple.

Say an item does not appear in the search list but I want the user to be able to add his own item. The user can enter in his own item or select from the dropdown. Is this possible with the current select2?

James.

initSOpen not defined

Newest version gives a JS error:

Uncaught ReferenceError: initS2Open is not defined

And leaves the spinning icon hanging, without loading select2

plaginEvents dont works

The widget works until I insert 'plaginEvents'. This is my widget:

echo Select2::widget(
[
'name' => $fname,
'value' => $fname,
'data' => $fval,
'options' => ['multiple' => true],
'plaginEvents' => ['change' => 'function(){alert("change");}']
]);

This is my Error:

exception 'yii\base\UnknownPropertyException' with message 'Setting unknown property: kartik\select2\Select2::plaginEvents' in C:\openserver\OpenServer\domains\prodamgitaru.ru\vendor\yiisoft\yii2\base\Component.php:197

using without bootstarp

Hi,
I'm using this widget in my project. I'm just curious is it possible to eliminate bootstrap css & js calls in that. I have custom frontend theme and bootstrap's default css & js cannot be used. I don't want to disturb your any of widget.

Hiding widget

How do I hide widget? Simple JQuery code below does not work.
Google only gives how to hide dropdown. I want to hide whole widget in some case

$("#widget_id").hide() // show(false) does not work

Can't type anything if select2 in modal

After recent updates typing wasn't working in any of my select2 widgets that were inside bootstrap modals. Then I found this solution which seems to have worked for me: select2/select2#1436

It was working fine before I did the update on everything and now I don't know what the cause of the problem is (either update of select2 widget or yii2 update), but since that solution is from almost 2 years ago I have a feeling that the problem is somewhere in your widget, because it was updated very recently.

Select2 2.0.0 doesn't work in modal demo

When you look at your demo that uses the modal dialog, you will see that the search box is not responsive and the search does not work. I've seen the problem appear in my code after updating to 2.0.0

Guide for migration

Hey,

Can you provide a guide to migrate from the version 1.0.1 to version 2.0 ?

Cannot Install 1.1.0 via Composer

Hi Kartik,
First of all, thanks for these useful plugins and widgets. I am trying to update from 1.0.0 to 1.1.0 in my application via composer, but its not updating the script files.

I am very new to composer and repositories, Correct me if I am wrong, but i think you need to release the latest version of your repository.

Ajax search and results with optgroup

Hello,

Is there any way to use the ajax search, and return the results with an optgroup, to have the result displayed similar to the normal select2 dropdown (in your examples you have the states optgroups).

Could find anything to work.

Thanks!

Wrong behavior with model tags + new tags

I am experiencing some problems after upgrading from version 1 to version 2.0.1. (version 1 works ok)

I'm trying to use the tags coming from the model and insert new tags.

1 - The tags coming from the model are shown in field correctly.
2 - I try to insert a new tag between existing ones
3 - When I press the enter key, tags coming from the model disappear keeping only the new tag created.

Have you seen this happen?

My code:

<?php
                $url = Url::to(['keywords-list']);
            ?>
            <?= $form->field($model, 'palavras_chaves_imagens')->widget( Select2::classname(), [
                'language' => 'pt-BR',
                'options' => ['placeholder' => 'Selecione as palavras chaves ...'],
                'pluginOptions' => [
                        'allowClear' => false,
                        #'id' => new JsExpression(" function(params){ return params.id; } "),
                        'maximumInputLength' => 15,
                        'minimumInputLength' => 2,
                        'multiple'=>true,
                        'tags'=>true,
                        'tokenSeparators'=>[','],
                        'createTag'=> new JsExpression( "function (term, data) {
                            if ($(data).filter(function() {
                                return this.text.localeCompare(term)===0;
                            }).length===0) {
                                return { id: $.trim(term.term) + ' (nova tag)', text: $.trim(term.term) + ' (nova tag)' };
                            }
                        }"),
                        'ajax' => [
                            'url' => $url,
                            'delay' => 1000,
                            'dataType' => 'json',
                            'data' => new JsExpression('function(params) { return { search: params.term }; }'),
                            'processResults' => new JsExpression('function(data,params) { return { results: data.items }; }'),
                        ],
                        'initSelection'=> new JsExpression( "function(element, callback) {
                            //var id= $(element).attr('value');
                            var id= {$model->ima_id}
                            if (id !== '') {
                                $.ajax( \"{$url}\", {
                                    data: { id: id },
                                    dataType: 'json'
                                }).done(function(data) { callback(data.items); });
                            }
                        }"),
                ],
            ]); ?>

List with item '0' shows id instead of display value.

Hello, when using a model to populate a select2, e.g. a table with just id and name fields. If there's one record with name='0', and you select it, the select2 will display the id instead after the selection. It works fine with other records. Can this be fixed? Thank you.

reload select2 with pjax

I've embedded a select2 field inside of a pjax container. The idea is to refresh the list of options without reloading the entire form (the user has an "add" button to add more options to the select list). The pjax reload works, but then the widget only shows a reloading rotating arrow, it is not fully rendered after the pjax refresh. I'm guessing that some js event is also necessary to complete the reload. Can you please advise how to get this working?
Alternatively, would using the ajax feature be a better idea than what I described above?

Thanks.

reload select2 after activeForm was submitted

Hi. I'm using the widget with ActiveForm like in the demo examples on your page. But when I submit the form and get it reloaded, the select2 fields are spinning all the time. The fields are not loaded completely as full pretty Select2. In returned page code I see just an input with value. I can see the id I've selected by value before through the 'pluginLoading' => false -- in this case the field is displayed as simple input with Id of previously selected item.
I've just thought it looks like the same issue with #18 but it's closed. Could you describe the answer you found out more completely?

Thanks.

JS error on clear

When clicking on clear button JS error will appear:

Uncaught TypeError: Cannot set property 'prevented' of undefined

You can reproduce it in demos page.

Get id from selected option in select2 widget

When we used select2, we would get more than 1 option, then we can select 1 of them. In the process of firebug console, i got json data results such as id & text of all the available options. The question is how can i get the id from the selected option? Thank you.

CSS issue with GridView after 2.0 upgrade

After updating to the 2.0 version, when using Select2 with GridView it defaults to "display: table", so width does not scale with it's contents.
clipboard01

Only happens with THEME_KRAJEE and THEME_BOOTSTRAP.

pluginEvents

That is in your docs:

pluginEvents = [
    "change" => "function() { log('change'); }",
    "select2-open" => "function() { log('open'); }",
    "select2-opening" => "function() { log('select2-opening'); }",
    "select2-close" => "function() { log('close'); }",
    "select2-highlight" => "function() { log('highlight'); }",
    "select2-removing" => "function() { log('removing'); }",
    "select2-removed" => "function() { log('removed'); }",
    "select2-loaded" => "function() { log('loaded'); }",
    "select2-focus" => "function() { log('focus'); }",
    "select2-blur" => "function() { log('blur'); }",
];

it is not working

can not set initValueText when using ajax and templates

I use ajax and template with select2. But can not init the default selection value with "initValueText". However, if I do not use template, the initValueText works fine

        echo $form->field($model, 'endField')->widget(Select2::classname(), [
            'name' => 'field-select2',
            'initValueText' => 'kartik-v/yii2-widgets',
            'value' => '672',
            'options' => [
                'placeholder' => 'Search for a repo ...'
            ],
            'pluginOptions' => [
                'allowClear' => true,
                'minimumInputLength' => 2,
                'ajax' => [
                    'url' => Url::to([
                        'fields/ajaxfields', 'pid'=>$model->startPid
                    ]),
                    'dataType' => 'json',
                    'data' => new JsExpression('function(params) { return {q:params.term}; }'),
                    'cache' => true
                ],
                'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
                'templateResult' => new JsExpression('formatRepo'),
                'templateSelection' => new JsExpression('formatRepoSelection')
            ]
        ]);

Select2 4.0.0

Just a heads up, Select2 4.0.0 was released about two weeks ago.

One problem in IE

After last update all Select2 widgets is open always in IE.

image

And it can not be closed.

In other browsers, such problems are not noticed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.