How To Load Model Data To Select2 Dropdown Which Uses Ajax Filtering In Yii

[font=“Arial,”][size=“2”]I use the following select2 Yii widget in my view to populate a drop-down list. Since the data necessary for the preparation of the select list consists of more than 2K records I use select2 with minimumInputLength parameter and an ajax query to generate partial result of the list based on user input. If I create a new record I have no problem at all. It populates everything fine and I can save data to my database. However I don’t know how to load saved data back to this drop-down during my update action. I read somewhere that initselection intended for this purpose but I couldn’t figure out how to use it.[/size][/font]

[font="Arial,"][size="2"]Can someone help me out on this?[/size][/font]

[font="Arial,"][size="2"]My view:[/size][/font]





$this->widget('ext.select2.ESelect2', array(

				'selector' => '#EtelOsszerendeles_osszetevo_id',

				'options'  => array(

						'allowClear'=>true,

						'placeholder'=>'Kérem válasszon összetevőt!',

						'minimumInputLength' => 3,

						'ajax' => array(

								'url' => Yii::app()->createUrl('etelOsszerendeles/filterOsszetevo'),

								'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 }; }',

						),

				),

              ));?>



[font=“Arial,”]My controller’s action filter:[/font]





public function actionFilterOsszetevo()

	{

		$list =EtelOsszetevo::model()->findAll('nev like :osszetevo_neve',array(':osszetevo_neve'=>"%".$_GET['q']."%"));

		$result = array();

		foreach ($list as $item){

			$result[] = array(

					'id'=>$item->id,

					'text'=>$item->nev,

			);

		}

		echo CJSON::encode($result);

	}



Hello

I do not answer your question because I do not know. But I want to ask: Where you are putting the method?

A I do not load my data, and as a probe nor listata. I do not know if you could help me with that. }




				 <?php 

					echo CHtml::hiddenField('Id_Usuario','', array('class' => ''));  					

				        $this->widget('ext.select2.ESelect2',array(

				           'selector' => '#Id_Usuario',

				           'model'=>$model,

				           'attribute' => 'Id_Usuario',

				        //   'data'=>CHtml::listData(Usuarios::model()->findAll(array('order'=>'Nombres')), 'Id_Usuario', 'nombreCompleto'),

				           'options'  => array(				            

					           'allowClear'=>true,				           

					           'placeholder'=>'Selecione el Demandante',

					         //'minimumInputLength' => 4, 

					           'ajax' => array(

					           'url'=>array('FiltroCargo'),

					        // 'url' => Yii::app()->createUrl('dpeticion/FiltroCargo'),

					            'dataType' => 'json',

					        //  'type'=>'GET',

					            '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 };

					             }',

					              

                               'formatSelection'    => 'js: function(data) {

                                    return data.title;

                                }',

                               'initSelection'      => 'js: function(element, callback) {

                                    var elementText = $(element).data("init-text");

                                    callback({"title":elementText});

                               }'

					        ),

				       ),				         

				    ));

				 ?>



There are some lines that are with that comment and tried and do not work

My controller




 		public function actionFiltroCargo(){

             

                   $lista =Usuarios::model()->findAll('Nombres like :term',array(':term'=>"%".$_GET['q']."%"));

                   $reusultados = array();


                   foreach ($lista as $list){

          			 $reusultados[] = array(          			 	

                        'id'=>$list->Id_Usuario,

                        'text'=>  $list->Nombres,

          	 ); 

        	}

                echo CJSON::encode($reusultados);   

                    

        }



Sorry for my english

Thanks

I should have been saved as a string so you need to explode it back into an array so it can ready the data or it will only show only one and most of the time none.


public function actionUpdate()

{

other code

        /*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())

                $posttags = explode(',', $model->tags);

  $model->tags = $posttags;

        /*end selec2*/  


other code

      

));

}

@keniy here is what i use to show related data


<?php

$this->widget('ext.select2.ESelect2',array(

'model'=>$model,

'attribute'=>'mfg_id',

'htmlOptions'=>array(

'style'=>'width:100%',

'multiple'=>true,//can put to false to only allow one value

),

'data' => CHtml::listData(

Companies::model()->findAll(

array('order' => 'name ASC')),

'id',

'name'

),

));

?> 

also to clear the forms with select 2 you can use this post i made

Thanks

Sorry for my late reply. I opened this thread on StackOverflow as well. Here is the topic. You may find some useful information there:

StackOverflow thread

Hello

After trying both, the data is loaded. It is very rare, because it is not normally called the url, but this way.




	public function actionListarDemandantes(){

         

               $lista =Usuarios::model()->findAll('Nombres like :term or Apellidos like :term' ,array(':term'=>"%".$_GET['q']."%"));

               $reusultados = array();

               foreach ($lista as $model){

      		     $reusultados[] = array(          			 	

                    'id'=>$model->Id_Usuario,                        

                    'text'=>$model->Nombres.' '.$model->Apellidos,

      	 ); 

    	}

            echo CJSON::encode($reusultados);                       

    }



controller




			echo CHtml::hiddenField('Id_Usuario');  					

			$this->widget('ext.select2.ESelect2',array(

			'selector' => '#Id_Usuario',

			'model'=>$model,

			'attribute' => 'Id_Usuario',

			'value'=>$model->Id_Usuario,

			'options'  => array(				            

			        'allowClear'=>true,				           

				'placeholder'=>'Selecione el Demandante',	

				'width' => '220px',			         

				'ajax'=>array(


                                //correction, name action 

				'url'=>$this->createUrl('ListarDemandantes'),


				'dataType' => 'json',

				'type'=>'GET',

				'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 };

						            

				}',

						              

	                        'formatSelection'=>'js: function(data) {

	                                    return data.title;

	                                }',

	                         'initSelection'=>'js: function(element, callback) {

	                                    var elementText = $(element).data("init-text");

	                                    callback({"title":elementText});

	                         }',

				),					             

				 ),				         

				 ));




The problem is that it does not save data. Displays the following error: Error 404, The requested page does not exist.

Do not save the id to select. Must not be null. Do not know why others are saved them perfectly, while my turn to change things to make it work …

Thanks. Sorry for my english