[Solved] Dependent Dropdownlist With Cjuiautocomplete

Hi all, this is my 1st post :)

I want to create dependent dropdownlist similar to this wiki, but in my case i want to use CJuiAutoComplete instead of dropdownlist to populating the second dropdownlist. I’ve already make my CJuiAutoComplete works, but cannot figure it out how to populate the dropdownlist.

Thanks in advance.

After spending a couple hours at doing some test, finally i end up with this solution. I’m not sure if my code good enough considering as best practice, but it works.

The autocomplete TextField:




        <?php echo $form->hiddenField($model,'customer_id',array()); ?>

        <?php $this->widget('zii.widgets.jui.CJuiAutoComplete',

        array(

              'model'=>$model,

              'attribute'=>'corp_code',

              'source'=>$this->createUrl('customer/getcustomer'),

              'options'=>

                 array(

                       'minLength'=>3,

                       'showAnim'=>'fold',

                       'select'=>"js:function(event, ui) {

                          $('#SupportRequest_customer_id').val(ui.item.id);

                          getPackages(ui.item.id);

                                 }"

                        ),

              'cssFile'=>false,

        )); 

        ?>



My getcostumer controller action.




    public function actionGetCustomer()

    {

        if (isset($_GET['term']))

        {

            $criteria=new CDbCriteria(array(                    

                                'alias'=>'customer',

                                'condition'=>"customer.corp_code like '" . $_GET['term'] . "%'",

                        ));

          

            $dataProvider=new CActiveDataProvider('Customer', array(

                                    'criteria'=>$criteria,

                                    'pagination' => false,

                                ));    

     

            $customers = $dataProvider->getData();


            $return_array = array();

            foreach ($customers as $customer)

            {

                $return_array[] = array(

                    'label' => $customer->corp_code . ' - ' . $customer->corp_name,

                    'value' => $customer->corp_code,

                    'id' => $customer->id,

                    );

            }

            echo CJSON::encode($return_array);

        }

    }



Register Javascript code in view.




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

        function getPackages(cid){

            $.ajax({

                url: '". $this->createUrl('dynamicpackage')."',

                data: 'cid='+cid,  

                success: function(packages) {

                         $('#".CHtml::activeId($model, 'package_id')."').html(packages);

                      }

            });

        }

        $(document).ready(function() {

            getPackages($('#SupportRequest_customer_id').val());

        });     

        ",CClientScript::POS_END);

?>



Controller called by Ajax for populating dropdownlist:




    public function actionDynamicPackage()

    {


        $data=Package::model()->findAll('customer_id=:customer_id', 

                      array(':customer_id'=>(int)$_GET['cid']));

     

        $data=CHtml::listData($data,'id','sp_number');

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

        {

            echo CHtml::tag('option',

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

        }

    }  



An empty dropdownlist to be bind with the data from ajax:




<?php echo $form->dropDownList($model,'package_id',array(), array('empty'=>'- Select -')); ?>



That’s it! Happy coding!!

I wanted the same, however I could not get the previous example to work. see below how I do it

In view

$this->createurl points to the controller, here below it is named autocompletetest.





<input id="searchterm" type="text" /> <button id="search">search</button>


<?php 

Yii::app()->clientScript->registerScript('search', "


$('#searchterm').keyup(function(e){

     var terms = $(this).val();

      $.ajax({ 

          url: '" .$this->createUrl('autocompletetest'). "', // JQuery loads serverside php

          data: 'term='+terms, 

          dataType: 'json', // Choosing a JSON datatype

          success: function(data) // Variable data contains the data we get from serverside

          {

          select = document.getElementById('autocompletelist');

          select.options.length = 0;

                $.each(data, function(i, value) {

                    $('#autocompletelist').append($('<option>').text(value).attr('value', value));

                 });

            }

        });


    });




");

    

    echo CHtml::dropDownList('autocompletelist', null, $list, array('empty' => '(Select a name)','size'=>10, 'style'=>'width:360px;'  ));


?>



in controller:




public function actionAutocompleteTest() {

                $searchterm = '';

                $getresult = '';

                $result = '';


                if (isset($_GET['term'])) {


                $criteria = new CDbCriteria();

                $criteria->condition = 'somecolumn LIKE :searchterm';  // < replace somecolumn with a columns from your database

                $criteria->params = array(': searchterm'=>'%'. $_GET['term'] . '%');

                $getresult = YOURMODEL::model()->findAll($criteria);  // < replace YOURMODEL with the name of your model

                $result = CHtml::listData($getresult, 'id', 'location');


                }

                echo CJSON::encode($res);

                Yii::app()->end();

        }



Enjoy :slight_smile: