tirsdag den 8. oktober 2013

Yii Select2, How to initiated selected (saved) values


To achieve this

In this scenarie we have 5 choice from which 3 are already saved and we wish to represent this selection again in our form by YiiBooster

Pay attention to text colors.

This widget call:

$this->widget(
        'bootstrap.widgets.TbSelect2',
        array(
            'asDropDownList' => false,
            'name' => 'userRoles',
            'data'=>$userRoles,
            'options' => array( // selected options by default
               
            ),
            'options' => array(           
                'tags' => $userRoles, // Array
                'placeholder' => '',
                'width' => '220px',
                'tokenSeparators' => array(',', ' '),
                'initSelection'=>'js:function(element, callback){
                    var data = [];
                    '.$s2InitStr.'
                    callback(data);
                }',
            ),
        )
    );

Produces this JS code

jQuery('#userRoles').select2(
{
'tags':['Admin','Authenticated','Guest','representative','yderzonen'],
'placeholder':'',
'width':'220px',
'tokenSeparators':[',',' '],
'initSelection':function(element, callback){
var data = [];
data.push({id:'Admin' , text: 'Admin'});
data.push({id:'Authenticated' , text: 'Authenticated'});
data.push({id:'representative' , text: 'representative'});
callback(data);
}});
 
 
After this is done you have to produce this JS code:
 
jQuery(function($) {
 
 /**
  * The selectors must be changed to match your Select2 ID 
  */
 
  $('#s2id_userRoles').select2('val','Admin');
  $('#s2id_userRoles').select2('val','Authenticated');
  $('#s2id_userRoles').select2('val','representative');
 
}); 


More Documentation
 
http://ivaynberg.github.io/select2/ 
http://stackoverflow.com/questions/15174635/proper-usage-of-jquery-select2s-initselection-callback-with-remote-data
http://yiibooster.clevertech.biz/widgets/forms_inputs/view/select2.html#config
 
If you have a better idea please leave a link. Thanks
 

Ingen kommentarer:

Send en kommentar