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
- Assets update (select2 3.1)
- Added translation support, (id,pl)
- Credits: https://github.com/nineinchnick
- 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
Drini
took me some modification to enable multiple selects.. just thought you wanted to know.
Example Code
Hi,
the example code not really helpful. How to enable the multiple select in select2 widget?
$("#e2").select2({ placeholder: "Select a State", allowClear: true }); $("#e2_2").select2({ placeholder: "Select a State" });
All the example code above need write inside the script as below?? Somehow it can't work after do like that, need more help pls.
<script> $(document).ready(function() { $("#e1").select2(); }); </script>
jowen start by reading my previous comment
then, read the select2 documentation, it clearly says the select needs a multiple="" attribut. This extension misses the option but it is easy to do.
class ESelect2 extends CInputWidget { public $multiple=false;
then a bit down
public function run() { list($this->name,$this->id)=$this->resolveNameId(); if($this->multiple) $this->htmlOptions['multiple']='foo'; if($this->hasModel())
<?php $this->widget('ext.select2.ESelect2',array( 'model'=>$model, 'attribute'=>'attrName', 'data'=>array( 0=>'Nol', 1=>'Satu', 2=>'Dua', ),'multiple'=>true ); ?> and done..
Nice extension
Since now I was using "echosen". But this wrapper is many many better! Thanks for such good doc!
placeholder can't work for me..
Hi Drini,
Is there any error for the code below?? The placeholder can't show at all.. Thanks.
<link href="select2.css" rel="stylesheet"/> <script src="select2.js"></script> <script> $(document).ready(function() { $("#e2").select2({placeholder: "Select a State", allowClear: true}); }); </script> <?php $this->widget('ext.select2.ESelect2', array( 'id' => 'e2', 'options' => array( 'width' => '250px;', ), 'data' => array( 1 => 'Nolrtrtrttr', 2 => 'Satu', 3 => 'Dua', ), 'multiple' => true, )); ?>
CInputWidget htmlOptions-detail
<?php $this->widget('ext.select2.ESelect2',array( 'model'=>$model, 'attribute'=>'attrName', 'data'=>array( 0=>'Nol', 1=>'Satu', 2=>'Dua', ), 'htmlOptions'=>array( 'multiple'=>'multiple' ) ); ?>
CInputWidget htmlOptions-detail
Sorry, my english is bad...
<?php $data['']=''; $data=$data+CHtml::listData(Country::model()->findAll(),'iso_alpha2','name'); //$data=CHtml::listData(YourModel::model()->findAll(),'id','label'); //$data[0]='Your placeholder: '; $this->widget('ext.select2.ESelect2',array( 'model'=>$model, 'attribute'=>'attrName', 'data'=>$data, 'htmlOptions'=>array( 'multiple'=>'multiple' ) ); ?>
Cannot use "placeholder" options [fixed]
I'm trying to use placeholder options. Here is my code:
<?php $data=CHtml::listData(Country::model()->findAll(),'id','name'); $this->widget('ext.select2.ESelect2',array( 'model'=>$model, 'attribute'=>'countryid', 'data'=>$data, 'options'=>array( 'placeholder'=>'Select your country', 'allowClear'=>true, ), )); ?>
It rendered javascript like this..
[javascript] $('#WorldForm_countryid').select2({'placeholder':'Select your country','allowClear':true});
And, the placeholder is not working. Any suggestion?
Thanks!
[EDIT]
Here is the solution
$data['']=''; $data=$data+CHtml::listData(Provinsi::model()->findAll(),'id','nama'); $this->widget('ext.select2.ESelect2',array( 'model'=>$model, 'attribute'=>'provinsiid', 'data'=>$data, 'options'=>array( 'placeholder'=>'Pilih Provinsi', 'allowClear'=>true, ), 'htmlOptions'=>array( 'options'=>array( ''=>array('value'=>null,'selected'=>null), ), ), )); ?>
Using above syntax will make placeholder working along with allowClear. Thanks @nk913 for helping me! :D
How change ESelect2 value to "placeholder" using jQuery?
Hi, I want to change my Select2 widget value programatically using jQuery.
For example i want to do this:
[javascript] $('#buttonclear').click(function() { // What should I write here to change my widget value // to its placeholder value? });
I already trying
~~~
[javascript]
$('#myESelect2').empty();
~~~
But it just not working. Any sugestion?
Thanks!
[EDIT]
Just found it. You can use
~~~
[javascript]
$("#myESelect2").val(null).trigger("change");
~~~
It will revert its value to placeholder value
Error in release select2-20120619
line 42
$bu=Yii::app()->assetManager->publish(dirname(__FILE__).'/assets/select2-2.1');
must be I think
line 42
$bu=Yii::app()->assetManager->publish(dirname(__FILE__).'/assets/');
Can You Publish ChangeLog?
optgroup still don`t work in this last release
@porcelanosa
@Porcelanosa thank you, please check 20120620 release it's include opt group
Width of block
Thanx! OptGroup work pefect
I use twitter bootstrap: and when I want to set width for select by class="span4" for example layout is crashed.
How and when you calculate the width of block and how I can set it?
_POST is array
if multiplу=false the $_POST is array anyway
In last version it been intenger or string
UPD i`m sorry In previos version POSt is array too
tags
To support the 'tags' feature (adding free values, no need to select from the list) of select2 you have to output a textField instead of a dropdownlist.
So you have to change the source like below:
public function run() { ... $this->htmlOptions['id']=$this->id; $this->htmlOptions['name']=$this->name; if($this->hasModel()) { if(isset($this->options['tags'])) echo CHtml::activeTextField($this->model,$this->attribute,$this->htmlOptions); else echo CHtml::activeDropDownList($this->model,$this->attribute,$this->data,$this->htmlOptions); } else { if(isset($this->options['tags'])) echo CHtml::textField($this->name,$this->value,$this->htmlOptions); else echo CHtml::dropDownList($this->name,$this->value,$this->data,$this->htmlOptions); }
Usage:
Assign 'options.tags' instead of the 'data' attribute:
$this->widget('ext.select2.ESelect2',array( 'model'=>$model, 'attribute'=>'attrName', 'options'=>array( 'tags'=>array( 0=>'Nol2', 1=>'Satu', 2=>'Dua', ), ), );
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?
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);
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
&lt;b&gt;t&lt;/b&gt;ext
instead of<b>t</b>ext
How to correctly HTML-encode the data? Thank you.
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...
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
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.
another initSelection function
can be found here
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.
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
Using Eselect2 together with Multimodelform Extension
The details how one should use this excellent widget together with Multimodelform extension are described here.
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
Problem with large number os objects
I'm trying to use select2 (without ajax) but I'm having problems when using a large number of objects (around 10k). When i click on the generated select the browser freezes and give me a message "The script doesn't respond" with an option to wait or abort.
Any thoughts anyone?
infinite scrolling
@Bianchi for large lists (above 100 items) i suggest you use the infinite scrolling/ajax response http://ivaynberg.github.io/select2/#infinite
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?
Search onclick
Is it possible to only search, with ajax, after the user click on a button?
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.
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!!
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. whereparent
is the foreign key:... 'initSelection'=>'js:function(element,callback){ var data={id:'.$model->parent_id.',text:"'.$model->parent->name.'"}; callback(data); }', ...
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', ), ));
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
how to save
how to save the data using this extension?
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.
already selected tags
Please tell me somebody, how to select tags already ! like on update.
@sefburhan
I think you mean pre-selecting values. This comment should help...
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 !!!!.
solved #15683
If someone has the same problem, solution follows:
Select2 Return
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, )); }
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' }); },
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; }', ), ));
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
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', ), ), ));
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.
Solved! Problem #18256
Thanks for your magnificent answer @MasterQ!
Helped me a lot. Thanks and God Bless!
Very helpfull extension
Thanks for this ext, very nice for me!
Really Good! How to implement Select2 in TbGridView?
I want to use Select2 Extension in TbGridView. I am using that extension in form, that's ok. But in case of TbGridView I facing problem.
<?php $this->widget('bootstrap.widgets.TbGridView',array( 'id'=>'rfpayment-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'columns'=>array( //'id', //'invoice_id', 'crn', //'ern', 'yr', //'feestructure_id', //I want to implement Select2 Extension here ... array( 'name' => 'feestructure_id', 'value' => '$data->feestructure->title', 'filter' => CHtml::listData(Feestr::model()->findAll(), 'id', 'title') ), // 'feestructure_status', // 'late_fee', // 'remarks', // 'postby_id', // 'verified', // 'created_at', // 'updated_at', // 'status', array( 'class'=>'bootstrap.widgets.TbButtonColumn', ), ), )); ?>
Limiting the number of selections
i want to use top limit. for example, the user selected only three values from all values. how can do it?
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.