Updating DropDownList after writing in TextField

Hello!,

I am trying to update a DropDownList with Ajax after writing in a TextField. The first textfield will be an autocomplete (which I already have) and after selecting a value, I’d like to update a DropdownList.

I want to use a Textfield because the user can choose between 50.000 values, so, It could be a large DropDownList!

Thanks in advance!

check out this Wiki Article

Thanks Angelo,

I knew that tutorial, but that was not what I needed. I wanted the DropDownList to update from an autocomplete textfield, and I finally got it, it does even hold the selected value after validation. This is the code (I guess it could be better, but it works):

The autocomplete TextField. The imporant part here is the calling to an external javascript function in the methodChain parameter:


<?php $this->widget('CAutoComplete',

          array(

                         //name of the html field that will be generated

             'name'=>CHtml::activeName($envio, 'cpEntrega'),

              'cacheLength'=>20,

              'mustMatch'=>true,

                         //replace controller/action with real ids

             'url'=>array('envios/AutoCompleteCP'),

             'max'=>10, //specifies the max number of items to display

             'value'=>$envio->cpEntrega,


                         //specifies the number of chars that must be entered

                         //before autocomplete initiates a lookup

             'minChars'=>1,

             'delay'=>300, //number of milliseconds before lookup occurs


             'matchCase'=>false, //match case when performing a lookup?


                         //any additional html attributes that go inside of

                         //the input field can be defined here

             'htmlOptions'=>array('size'=>'20'),


             'methodChain'=>".result(function(event,item){

                 creaDDL(item[0]);

                 })",


             ));

        ?>



The Autocomplete PHP function, in case anyone needs it. Anyway there’s a tutorial to do this:


public function actionAutoCompleteCP()

        {

           if(Yii::app()->request->isAjaxRequest && isset($_GET['q']))

           {

                /* q is the default GET variable name that is used by

                / the autocomplete widget to pass in user input

                */

              $name = $_GET['q'];

                        // this was set with the "max" attribute of the CAutoComplete widget

              $limit = min($_GET['limit'], 50);

              $criteria = new CDbCriteria;

              $criteria->distinct=true;

              $criteria->condition = "cp LIKE :sterm";

              $criteria->params = array(":sterm"=>"$name%");

              $criteria->limit = $limit;

              $arr = Poblaciones::model()->with("idProvincias0")->findAll($criteria);

              $returnVal = '';

              //echo(sizeof($userArray));

              foreach($arr as $account)

              {

                 $returnVal .= $account->getAttribute('cp').'|'

                                    .$account->getAttribute('nom_poblacion').'|'

                                             .$account->idProvincias0->provincia."\n";

              }

              echo $returnVal;

           }

        }




This is the javascript that binds the select element, and the "body onload" to load the select with data if there is any content in the input box.


<?php Yii::app()->clientScript->registerScript("0000","

    function creaDDL(element)

                 {

                    $.ajax({

                      url: '".$this->createUrl('envios/dynamicCities')."',

                      data: \"cp=\"+element,

                      success: function(msg) {

                        $('#".CHtml::activeId($envio, 'poblacionEntrega')."').html(msg);

                      }

                    });

                 }

                 $(document).ready(function() {

                  creaDDL($('#EnvioDummy_cpEntrega').val());

                   });",CClientScript::POS_END);?>



The PHP called by AJAX to search for the value passed as attribute


public function actionDynamiccities($cp)

        {

            $data=Poblaciones::model()->findAllByAttributes(array("cp"=>$cp));

            $data=CHtml::listData($data,'id_poblacion','nom_poblacion');

            foreach($data as $value=>$name)

            {

                echo CHtml::tag('option',

                        array('value'=>$name),CHtml::encode($name),true);

            }

        }

And we need an empty dropdownlist to be bind with the data from the ajax:


<?php echo $form->dropDownList($envio,'poblacionEntrega',array()); ?>

hi all

its good to see code for dropdown updation based on textfield value.

In this example are you trying to get the data from model for dropdown and please explain me this line

$criteria->params = array(":sterm"=>"$name%"); in your function

thanks

ramakrishna

":sterm" (which stands for search term) is used in the above line,


$criteria->condition = "cp LIKE :sterm";

The line you are asking about adds the definition for :sterm, as it is not a string or database column - it’s called a parameter. “:sterm” is being defined as the variable $name% - that’s special for SQL statements, as a “%” means “any characters”.

The code


$criteria->params = array(":sterm"=>"$name%");

is basically saying:

"Whenever ":sterm" is seen in the SQL statement, replace it with the value of "$name%".

Hope that makes sense.

thank you george.