select2

Wrapper for ivaynberg jQuery select2
53 followers

ESelect2 is a widget extension for Yii framework. This extension is a wrapper for Select2 Jquery plugin (https://github.com/ivaynberg/select2).

Requirements

  • Yii 1.1 or above (tested on 1.1.10)

Usage

  • Extract the downloaded file to your application extensions directory
  • Just place the following code inside your view file:
// Working with selector
$tags=array('Satu','Dua','Tiga');
echo CHtml::textField('test','',array('id'=>'test'));
$this->widget('ext.select2.ESelect2',array(
  'selector'=>'#test',
  'options'=>array(
    'tags'=>$tags,
  ),
));
 
<?php $this->widget('ext.select2.ESelect2',array(
  'name'=>'selectInput',
  'data'=>array(
    0=>'Nol',
    1=>'Satu',
    2=>'Dua',
  ),
); ?>
 
// Working with model
<?php $this->widget('ext.select2.ESelect2',array(
  'model'=>$model,
  'attribute'=>'attrName',
  'data'=>array(
    0=>'Nol',
    1=>'Satu',
    2=>'Dua',
  ),
); ?>
 
 
// Optgroup
$data=array(
  'one'=>array(
    '1'=>'Satu',
    '2'=>'Dua',
    '3'=>'Tiga',
  ),
  'two'=>array(
    '4'=>'Sidji',
    '5'=>'Loro',
    '6'=>'Telu',
  ),
  'three'=>array(
    '7'=>'Hiji',
    '8'=>'Dua',
    '9'=>'Tilu',
  ),
);
 
$this->widget('ext.select2.ESelect2',array(
  'name'=>'testing',
  'data'=>$data,
)); 
 
 
$data=array(
  '1'=>'Satu',
  '2'=>'Dua',
  '3'=>'Tiga',
);
 
 
// Multiple data
$this->widget('ext.select2.ESelect2',array(
  'name'=>'ajebajeb',
  'data'=>$data,
  'htmlOptions'=>array(
    'multiple'=>'multiple',
  ),
));
 
// Placeholder
$this->widget('ext.select2.ESelect2',array(
  'name'=>'asik2x',
  'data'=>$data,
  'options'=>array(
    'placeholder'=>'Keren ya?',
    'allowClear'=>true,
  ),
));
?>

Resources

Changes

  • February 15, 2013
    • Update to select2 3.3
  • November 29, 2012
    • Update to select2 3.2, supporting jQuery events, new public method init()
  • September 13, 2012
    • Removing scriptPosition property (https://github.com/anggiaj/ESelect2/commit/9f7cf464f9ba16939ef57483fe71c2348c4b9732)
  • August 21, 2012
  • July 09, 2012
    • New public property $selector, to select any input[type=text] or other Html element
    • jQuery select2 fixes #192
  • June 20, 2012
    • Opt group and assets path fix (thanks to Porcelanosa)
  • June 19, 2012
    • Placeholder fix

Total 20 comments

#13618 report it
A.Miguel at 2013/06/11 07:32pm
Can't make

Hi

When attaching an ajax call to the ESelect2 I can't get any dropdownlist on the gui.

View:

$this->widget('ext.select2.ESelect2',
       array(
            'selector' => "#myemployee",
            'options'  => array(
                'width'              => '100%',
                'height'             => '500px',
                'placeholder'        => 'Search Employee',
                'minimumInputLength' => 0,
                'ajax'               => array(
                    'url'      => Yii::app()->createUrl('/employee/employee/ajaxFilter'),
                    'dataType' => 'jsonp',
                    'data'     => 'js: function(term,page) {
                                         return {
                                             q: term,
                                         };
                                   }',
                    'results'  => 'js: function(data,page){
                                       return {results: data};
                                   }',
                ),
                'formatResult'       => 'js:function(data){
                     return data.name;
                 }',
                'formatSelection'    => 'js: function(data) {
                     return data.name;
                 }',
            ),
       ));

Controller:

public function ajaxFilter()
{
     $criteria = ...
     $models= Employee::model()->findAll($criteria);
 
     $result = array();
     foreach ($models AS $employee) {
         $result[] = array(
             'id'   => $employee->id,
             'name' => $employee->name,
         );
     }
     echo CJSON::encode($result);
}

What am I doing wrong?

Thanks Miguel

#13013 report it
Joze Senegacnik at 2013/04/28 07:40am
Using Eselect2 together with Multimodelform Extension

The details how one should use this excellent widget together with Multimodelform extension are described here.

#12675 report it
Daniel at 2013/04/05 12:36am
Add new option

Hi,

How could I add new option? I googled and found 'createSearchOptions', but don;t know how to use it.....

I tried by putting on the options array but the result is that select2 is not working ;(

Cheers,

Daniel

#12589 report it
Caio P. at 2013/03/30 11:07am
Couldn`t use ajax on github version

I got the updated version through github, and I needed to create a input hidden field to run ajax. I changed the run method, line 66:

if (isset($this->model)) {
    echo CHtml::dropDownList($name, $this->model->{$this->attribute}, $this->data, $this->htmlOptions);
} elseif (isset($this->data)) {
    echo CHtml::dropDownList($name, $this->value, $this->data, $this->htmlOptions);
} else {
    echo CHtml::hiddenField($name, $this->value, $this->htmlOptions);
}

Worked for me, hope it helps.

#12118 report it
schmunk at 2013/02/27 06:51pm
another initSelection function

can be found here

#12116 report it
c@cba at 2013/02/27 05:26pm
@Edgar Kuskov

Hi, you could try the suggestion in my comment below...

#12115 report it
Edgar Kuskov at 2013/02/27 04:55pm
Preselect values

Is there possibility to preselect or save the selection fo the form? Every time the form is validated and the errors are shown, the selection disappear?

#11964 report it
Tanguy at 2013/02/15 02:33pm
Dead asset...

select2.min.js : Version: 3.2 Timestamp: Mon Sep 10 10:38:04 PDT 2012

edit: fixed in 20130215 archive, thanks

#11943 report it
nk913 at 2013/02/14 12:15pm
Thank you

@Hatem Alimam, @nineinchnick Thank you

#11923 report it
nineinchnick at 2013/02/13 03:34am
new version

New version 3.3 is available.

#11889 report it
Hatem Alimam at 2013/02/11 10:31am
Some data are Lost

Hello,

I just want to point out something,

in the description of this extension for using multiple data, the $data elements must have unique ids, that would effect the view and the selection, just to avoid some elements to be removed since some have the same id.

this is the code in the extension description.

<?php
                // Optgroup
                $data=array(
                'one'=>array(
                    '1'=>'Satu',
                    '2'=>'Dua',
                    '3'=>'Tiga',
                ),
                'two'=>array(
                    '1'=>'Sidji',
                    '2'=>'Loro',
                    '3'=>'Telu',
                ),
                'three'=>array(
                    '1'=>'Hiji',
                    '2'=>'Dua',
                    '2'=>'Tilu',
                ),
                );
 
 
                $this->widget('ext.select2.ESelect2',array(
                'name'=>'ajebajeb',
                'data'=>$data,
                'htmlOptions'=>array(
                    'multiple'=>'multiple',                    
                   ),
                ));
                ?>

and this is how the $data must be defined.

Unique IDs

<?php
                // Optgroup
                $data=array(
                'one'=>array(
                    '1'=>'Satu',
                    '2'=>'Dua',
                    '3'=>'Tiga',
                ),
                'two'=>array(
                    '4'=>'Sidji',
                    '5'=>'Loro',
                    '6'=>'Telu',
                ),
                'three'=>array(
                    '7'=>'Hiji',
                    '8'=>'Dua',
                    '9'=>'Tilu',
                ),
                );
 
                ?>

I'm sorry this might appear as a beginner point, but I had a friend which had a problem in testing this extension as some elements were disappeared from the menu due the duplicate of the ids.

Thanks, nice written extension.

#11103 report it
jiaming at 2012/12/17 02:26am
@nk913

@nk913 Hi, I've read the documents carefully, but still i can't find those variables' sources...(like "state","movie" from the documents). I am not using any model to load the data here, instead, I just use some associative arrays (friends_id=>friends_name) to fill in the drop down. What should I do?

Thanks so much!

#11100 report it
nk913 at 2012/12/17 01:51am
Please refer to http://ivaynberg.github.com/select2/ docs

Please refer to http://ivaynberg.github.com/select2/, you will find the complete documentation about those functions

#11099 report it
jiaming at 2012/12/17 01:12am
@nk913

@nk913, Thanks for your reply!

I did checked the comment but I don't quite get where is the variable "movie" comes from.

function movieFormatResult(movie)

What does this should be , for example, in my case?

Thanks!

#11098 report it
nk913 at 2012/12/16 09:52pm
check the comment

@jiaming use formatSelection and formatResult options, please check this comment #c9090

#11087 report it
jiaming at 2012/12/15 04:09pm
How to format result?

Dear all, I have a dropdown like this:

<?php $this->widget('ext.select2.ESelect2',array(
  'model'=>$model,
  'attribute'=>'friends[]',
  'data'=>$list,
 'options'=>array(
    // 'placeholder'=>'Please enter or choose at least one friend to ask, max 100 friends.',
    'maximumSelectionSize'=>100,
    'width'=>'712px',
  ),
 'htmlOptions'=>array(
   'class'=>'category',
   'multiple'=>'multiple',
  ),
)); ?>

Is there a way i can format the result so it can show the avatar of the friends and the username ?

Thanks!

#10801 report it
c@cba at 2012/11/24 06:20pm
Example for the ""initSelection"" option

In one of my applications I needed to initialize the select2 instance with some preselected values, which I had to load via ajax. I had to tinker a bit with the initSelection option to get it to work.
Here is my code, in case anybody needs something similar...

In the view file we have:

$preselected_ids = $_POST['ExistingParents']; 
// the IDs of the preselected models in string-form like '125, 56' 
// these are stored in $_POST after one submits the form and returns to it due to errors.
// we don't want to lose the values that were selected before the initial submit, 
// thus the need for an initSelection-implementation...
echo CHtml::textField("ExistingParents", $preselected_ids, array('style'=>'width:50%'));
$this->widget('ext.select2.ESelect2',array(
  'selector'=>"#ExistingParents",
  'options'=>array(
    'allowClear'=>true,
    'minimumInputLength' => 2,
    'multiple'=>true,
    'initSelection'=>'js:function (element, callback) {
        var selected_data = [];
        $.ajax({
            type: "GET",
            url: "'.Yii::app()->createUrl('child/task/getParentsByIds').'",
            data: "ids='.$preselected_ids.'",
            dataType: "json",
            success: function(result) { 
                for (var key in result) {
                    if (result.hasOwnProperty(key)) {
                        selected_data.push({id: result[key].id, text: result[key].text});
                        callback(selected_data);
                    }
                }
            }
        });
    }',
    'ajax'=>array(
        'url'=>Yii::app()->createUrl('child/task/getParents'),
        'dataType'=>'json',
        'data'=>'js:function(term,page) { return {q: term, page_limit: 3, page: page}; }',
        'results'=>'js:function(data,page) { return {results: data}; }',
    ),
  ),
));

The action that is called via ajax and provides the preselected model-data looks like this:

public function actionGetParentsByIds() {
    $parents = Parents::model()->findAll("id IN (".$_GET['ids'].")");
    $results = array();
    foreach($parents as $p) {
        $results[] = array(
            'id' => $p->id, 
            'text' => $p->first_name.' '.$p->last_name.' ('.$p->insurance_number.')'
        );
    }
    echo CJSON::encode($results);
}


Thanks for this great extension and best regards...

#10759 report it
tomsea at 2012/11/21 03:59pm
HTML-encode

Hi, How to HTML-encode the displayed data?

As a example, one of the items displayed has the following string stored in the DB: <b>t</b>ext and I'd like to display it that way.

If you use the following:

'data'=>CHtml::listData(User::model()->findAll(), 'id', 'name')

The data won't be HTML-encoded and will be presented as-is. This is, the HTML will be rendered and in this example it will display as: text (with the 't' in bold) Yii documentation suggests to use encodeArray. However, if you do the following:

'data'=>CHtml::encodeArray(CHtml::listData(User::model()->findAll(), 'id', 'name'))

The data will be presented as if it was double HTML-encoded. This is, it will show &amp;lt;b&amp;gt;t&amp;lt;/b&amp;gt;ext instead of <b>t</b>ext

How to correctly HTML-encode the data? Thank you.

#9090 report it
nk913 at 2012/07/19 03:08am
Ajax example

@dkrochmalny

<?php echo CHtml::textField('movieSearch','',array('class'=>'span5')); ?>
<?php $this->widget('ext.select2.ESelect2',array(
'selector'=>'#movieSearch',
'options'=>array(
  'placeholder'=>'Search a movie',
  'minimumInputLength'=>1,
  'ajax'=>array(
    'url'=>'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
    'dataType'=>'jsonp',
    'data'=>'js:function(term,page){
      return {
        q: term, 
        page_limit: 10,
        apikey: "e5mnmyr86jzb9dhae3ksgd73" // Please create your own key!
      };
    }',
    'results'=>'js:function(data,page){
      return {results: data.movies};
    }',
  ),
  'formatResult'=>'js:movieFormatResult',
  'formatSelection'=>'js:movieFormatSelection',      
),
)); ?>
 
<?php
$cs=Yii::app()->clientScript;
$cs->registerScript('select2_index_script',"
 
function movieFormatResult(movie) {
    var markup = \"<table class='movie-result'><tr>\";
    if (movie.posters !== undefined && movie.posters.thumbnail !== undefined) {
        markup += \"<td class='movie-image'><img src='\" + movie.posters.thumbnail + \"'/></td>\";
    }
    markup += \"<td class='movie-info'><div class='movie-title'>\" + movie.title + \"</div>\";
    if (movie.critics_consensus !== undefined) {
        markup += \"<div class='movie-synopsis'>\" + movie.critics_consensus + \"</div>\";
    }
    else if (movie.synopsis !== undefined) {
        markup += \"<div class='movie-synopsis'>\" + movie.synopsis + \"</div>\";
    }
    markup += \"</td></tr></table>\"
    return markup;
}
 
function movieFormatSelection(movie) {
    return movie.title;
}
 
",CClientScript::POS_HEAD);
#9086 report it
deez at 2012/07/18 09:40am
AJAX?

Hey guys I have a dropdown that is dependent on the value input into a select 2 dropdown. I have made dependent dropdowns with a regular select box, but the select 2 widget doesn't have an attribute called AJAX. Can anyone help me with the syntax?

Leave a comment

Please to leave your comment.

Create extension