Yii 1.1: select2

Wrapper for ivaynberg jQuery select2
76 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

#18432 report it
Master Q at 2014/10/28 11:53am
Adding pre-selected values

@pjravs

I think I had your same need so I'm sharing my solution with you and anyone who could benefit and/or improve it.

In my view:

//these are the data I need to preload
$selected = CHtml::listData($model->protocolloSanitarios, 'id', 'descrizione');
$options = array();
foreach ($selected as $key => $value) { 
//here I create an array suitable for the 'options' attribute with my data marked as selected
    $options[$key]=array('selected'=>true);
}
 
 $this->widget('ext.select2.ESelect2',array(
  'name'=>'protocolloSanitarios',
  'data'=>CHtml::listData(ProtocolloSanitario::model()->findAll(), 'id', 'descrizione'), //the whole available list
  'htmlOptions'=>array(
    'options'=>$options, //the selected values
    'multiple'=>'multiple',
    'style'=>'width:530px',
  ),
  ));

Hope this can help.

#18256 report it
pjravs at 2014/10/07 09:39pm
Set Selected Value

Help! I want to select a specific value inside this dropdown list. The data inside are 1=>Direct, 2=>Corporate, 3=>Travel. I want to default the selected direct. Pls Help!

$data = ClientCat::model()->findAll();
                         $data = CHtml::listData($data,'clntcat_id','clntcat_desc'); 
                         $this->widget('ext.ESelect2.ESelect2',array(
                            'model'=>$clientcat,
                            'attribute'=>'clntcat_desc',
                            'data'=>$data,
                            'options'=>array(
                                'placeholder'=>'Select Client Category..',
                                'allowClear'=>true,
                            ),   
                            'htmlOptions'=>array(
                                'onchange'=>'resetCat();',
                                'style'=>'width:35%;',
                                    'ajax'=>array(
                                        'type'=>'POST', 
                                        'url'=>CController::createUrl('updatetype'),
                                        'update'=>'#ClientType_clntype_name',                                   
                                    ),                                                              
                                ),
                          ));
#17286 report it
keiny at 2014/05/19 02:05pm
data not loaded

A I do not load my data.

So I have

<?php 
                echo CHtml::hiddenField('Id_Usuario','', array('class' => ''));  
                        $this->widget('ext.select2.ESelect2',array(
                           'selector' => '#Id_Usuario',
                         //  'model'=>$model,
                         //  'attribute' => 'Usuarios[]',
                        //   'data' =>CHtml::listData(Usuarios::model()->findAll(), 'Id_Usuario', 'Nombres'),
                           'attribute' => 'Id_Usuario',
                            'name'=>'Id_Usuario',
                           'options'  => array(                         
                           'allowClear'=>true,                         
                           'placeholder'=>'Selecione el Demandante',
                           //'minimumInputLength' => 4, 
                           'ajax' => array(
                        //  'url'=>Yii::app()->createUrl('ListarCiudadanos'),// Yii::app()->createUrl('Dpeticion/ListarCiudadanos'),
                            'dataType' => 'json',
                            'type'=>'GET',
                           // 'quietMillis'=> 100,
                            'data' => 'js: function(text,page) {
                                    return {
                                        term: text, 
                                        page_limit: 10,
                                        page: page,
                                    };
                                }',
 
                            'results'=>'js:function(data,page) { var more = (page * 10) < data.total; return {results: data, more:more };
                             }',
                            'formatResult'  => 'js:function(data){
                                 return data.name;
                              }',
                            'formatSelection' => 'js: function(data) {
                                return data.name;
                              }',
 
                        ),
                       ),
 
                        ));
                 ?>

This is my controller

public function actionListarCiudadanos($term)
         {
             $criteria = new CDbCriteria;
             $criteria->condition = "LOWER(Nombres) like LOWER(:term) or LOWER(Apellidos) like LOWER(:term)
             or (Id_Usuario) like LOWER(:term)";
             $criteria->params = array(':term'=> '%'.$_GET['term'].'%');
             $criteria->limit = 30;
             $models = Usuarios::model()->findAll($criteria);
             $arr = array();
             foreach($models as $model)
             {
                 $arr[] = array(
                 'label'=>($model->Nombres.' '.$model->Apellidos.' ('.$model->Id_Usuario.')'), // label for dropdown list
                 'value'=>($model->Nombres.' '.$model->Apellidos.' ('.$model->Id_Usuario.')'), // value for input field
                 'id'=>$model->Id_Usuario, // return value from autocomplete
                 );
             }
             echo CJSON::encode($arr);
         }

I do not show all records Thanks for your help

#16836 report it
ShreyasD at 2014/04/02 06:52am
Update not working....

i have following code in form but when i come back for update the value is not getting selected.
I have customers name in different table i am mapping them. any idea what i am doing wrong...

echo $form->textField($model,'cust_name',array('style'=>'width:220px;')); $this->widget('ext.select2.ESelect2', array('model'=>$model, 'selector' => '#HostCustForm_cust_name', 'options' => array( 'allowClear'=>false, 'placeholder' => 'Search a Customer', 'minimumInputLength' => 3, 'quietMillis'=>100, 'ajax' => array( 'url' => Yii::app()->createUrl('manage/host/customers'), 'dataType' => 'jsonp', 'data' => 'js: function(term,page) { return { q: term, page_limit: 10, }; }', 'results' => 'js: function(data,page){

                                return {results: data.details};
                            }',
                        ),

                         'formatResult'  => 'js:function(data){
                            return data.name;
                          }',
                        'formatSelection' => 'js: function(data) {
                            return data.name;
                        }',

                    ),
                ));
#16635 report it
Edgar Kuskov at 2014/03/13 10:23am
Ajax + Preselect

Hello,

i have a quesiton, if it is possible to combine AJAX and preselect values? Kind of:

$this->widget('ext.ESelect2.ESelect2',array(
                            'model' => $category,
                            'attribute' => 'productCategories',
                            'data' => $data,
                            'selected' => $selected,
                            'options'  => array(
                                    'allowClear'=>true,
                                    'minimumInputLength' => 2,
                                    'ajax' => array(
                                            .........
                                    ),
                                    'multiple'=>'multiple',
                            ),
                    ));

SOLUTION: Use in options the initSelection method:

initSelection: function(element, callback) {
callback({id: 1, text: 'default selection with id 1' });
},
#16218 report it
skworden at 2014/01/30 03:19pm
Losing data on update

I have a problem!

When i use the update form it loses the tags unless i input them again.

If i have tags Yii, Select2, Demo

in the field it will save them just fine and show them in the view.

When i go to update the field is blank. So if i save the form again without putting the tags back it it won't save.

But if i have just one tag i.e. Yii

It will show Yii in the update form as the value and save fine.

So it only does it if there are two or more tags

anyone have the same problem and know a solution?

<?php
$this->widget('ext.select2.ESelect2',array(
  'model'=>$model,
  'attribute'=>'tags',
  'options'=>array(
  ),
  'htmlOptions'=>array(
    'style'=>'width:100%',
    'multiple'=>'multiple',
 
),
'data'=>array(
    'Ready'=>'Ready',
    'Set'=>'Set',
    'Go'=>'Go',
  ),
));
?>

EDIT: SOLVED IT:

public function actionUpdate()
{
    Yii::app()->theme=Yii::app()->params['adminTheme'];
    $model=$this->loadModel();
 
    /*begin select2
        Select2 needs to have saved data in an array or it will dump the data on the     
        form.
        my data is saved in a single field named tags like so
        tag1, tag2, tag3, tag4, etc. so it needed to be exploded and converted to an array
        hope this helps other people
        */
    if($model->tags!==array())
        $model->tags = $posttags;
                $posttags = explode(',', $model->tags);
    /*end selec2*/  
    if(isset($_POST['Post']))
    {
        if($model->save())
            $this->redirect('../../admin');
    }
 
    $this->render('update',array(
        'model'=>$model,
    ));
}
#16150 report it
AndroideLP at 2014/01/23 06:57am
solved #15683

If someone has the same problem, solution follows: Select2 Return

#16149 report it
sefburhan at 2014/01/23 06:31am
c@cba yes pre-selection but for tags

Thanks for quick reply ! yes, i m talking about pre-selection but for tags NOT for mulitselect dropdown like http://ivaynberg.github.io/select2/, and link provided by u is't working !. In my case i want to show all the tags on desired field on update !!!!.

#16148 report it
c@cba at 2014/01/23 05:59am
@sefburhan

I think you mean pre-selecting values. This comment should help...

#16147 report it
sefburhan at 2014/01/23 04:57am
already selected tags

Please tell me somebody, how to select tags already ! like on update.

#15744 report it
Lexne at 2013/12/11 08:43am
Re: how to save

@NewMeem You get the data sent as post when you click on submit. Use this code to see what was posted:

echo '<pre>';print_r($_POST);echo'</pre>';

But does anyone know how I can make a select-all option? I'm using // Multiple data The generated javascript is way to huge for me to take the time to understand without documentation. I really would need this to work.

#15709 report it
NewMeem at 2013/12/09 02:44am
how to save

how to save the data using this extension?

#15683 report it
AndroideLP at 2013/12/06 08:42am
return ajax

I'm trying to work with select2 using ajax because my database query has more than 5,000 lines.

But the result of the ajax. it does not filter the query, bringing the entire query on the screen.

controller

public function actionFiltroCargo(){
                   $lista =CargoEspecifico::model()->findAll(array('limit'=>50)); 
                   $reusultados = array();
                   foreach ($lista as $list){
           $reusultados[] = array(
                        'id'=>$list->id,
                        'text'=>  $list->Nome,
           ); 
        }
                echo CJSON::encode($reusultados);   
 
                }

**form **

echo "<h2>Cargo especifico</h2>";
 
        echo CHtml::hiddenField('CargoespecSearch', '', array('class' => 'span5'));
        $this->widget('ext.select2.ESelect2',array(
            'selector' => '#CargoespecSearch',
            'options'  => array(
 
            'allowClear'=>true,
           'placeholder'=>'Selecione o Cargo Específico',
           'minimumInputLength' => 4, 
           'ajax' => array(
            'url' => Yii::app()->createUrl('curriculo/filtrocargo'),
            'dataType' => 'json',
            'quietMillis'=> 100,
            'data' => 'js: function(text,page) {
                    return {
                        q: text, 
                        page_limit: 10,
                        page: page,
                    };
                }',
            'results'=>'js:function(data,page) { var more = (page * 10) < data.total; return {results: data, more:more }; }',
        ),
       ),
 
        ));

printscreen

http://www.next4dev2.com/imagem/tela-error.jpg

#15670 report it
Lexne at 2013/12/05 10:24am
Select all for multiple data

Nice extension. I wonder, is there any way that I can get a "select all"-button for this? So instead of the user having to type every posiblity they could just click this button to select them all and populate it into the box? As a fast way for the user to select everyone exept two for example.

// Multiple data
$this->widget('ext.select2.ESelect2', array(
    'name' => 'ContactFormNewAffiliate[affiliates]',
    'model' => $model,
    'options'  => array(
        'placeholder' => $model->getAttributeLabel('affiliates'),
    ),
    'data' => CHtml::listData(
        Affiliate::model()->findAllByAttributes(
            array('available_for_public' => 1),
            array('order' => 'name ASC')
        ),
        'id',
        'name'
    ),
    'htmlOptions' => array(
        'multiple' => 'multiple',
        'class' => 'span4',
    ),
));
#15461 report it
toph at 2013/11/12 06:22pm
Setting the initial text to display for foreign key fields

If you are using the select2 with an existing foreign key, initSelection can be used to set the text e.g. where parent is the foreign key:

...
'initSelection'=>'js:function(element,callback){
    var data={id:'.$model->parent_id.',text:"'.$model->parent->name.'"};
    callback(data);
}',
...
#15371 report it
KateLab at 2013/11/02 05:11pm
How To Load Selected Data?

I have this in my _form:

$this->widget('ext.select2.ESelect2',array(
       'model'=>$model,
       'attribute' => 'authors[]',
       'data'=>CHtml::listData(
           Authors::model()->findAll(), 'AuthorId', 'AuthorName'),
       'options'  => array(
           'placeholder'=>'Select authors',
       ),
       'htmlOptions'=>array(
           'multiple'=>'multiple',
       ),
));

I use it on create method. How can I use it on update method with preload selected data?

Thank you!!

#14385 report it
kulkam at 2013/08/07 02:37pm
multiple and default value

I use select2 on a form:

$this->widget('ext.select2.ESelect2', array(
              'name' => 'Form[field]',
              'data' => CHtml::listData(Table::model()->findAll(), 'id', 'name'),
              'htmlOptions' => array(
                  'multiple' => 'multiple',
              ),
          ));

It works fine but I want to put there data if they exists in the "field". How to do this and how to format it? I was trying to use tags but it didn't work.

#14137 report it
Bianchi at 2013/07/22 02:08pm
Search onclick

Is it possible to only search, with ajax, after the user click on a button?

#14110 report it
Amini at 2013/07/19 11:38am
AutoComplete in a project

hi, thanks for very good extention. i have a problem. when i want type another data in select2(with htmlOptions multiple) can not do it. how can do? Namely i want used this in autocomplete format and suggest tags to user. Is it possible?

#14044 report it
Wiseon3 at 2013/07/15 02:18am
infinite scrolling

@Bianchi for large lists (above 100 items) i suggest you use the infinite scrolling/ajax response http://ivaynberg.github.io/select2/#infinite

Leave a comment

Please to leave your comment.

Create extension