Add additional value before ajax call when using Yii CAutoComplete

If you are like me who wish to add an additional value into Yii CAutoComplete and wondering how this can be done, it is pretty simple thanks to Ron Lavie. Assuming, you have the default ajax call on your controller which is "$_GET['q']", now, you would like to get a new value to be included into your controller called "$_GET['f']" and you are wondering what to do in order to get your value into Yii CAutoComplete before it fires ajax call to your controller, this is how you should do it.

'extraParams'=>array('f'=>"js:function(){return $(\"#f\").val();}"),

Using the extraParams, we can add in additional field before an ajax call to the controller. Here's a full illustration.

      $this->widget('CAutoComplete',
          array(
             'value'=> $text,
             'name'=>'nanny_name',
             'id' => 'nanny_name',
                         //replace controller/action with real ids
             'url'=>array('/task/admin/autoCompleteNannyLookup'),
             'max'=>10, //specifies the max number of items to display
                         //specifies the number of chars that must be entered
                         //before autocomplete initiates a lookup
             'minChars'=>1,
             'delay'=>500, //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'=>'40'),
             'extraParams'=>array('f'=>"js:function(){return $(\"#f\").val();}"),                                                                                   
             'methodChain'=>".result(function(event,item){\$(\"#updateValue\").val(item[1]);})",
          )); 
    ?>  

Now, whenever something is filled up on this CAutoComplete, it will search for the value in id "f" and included into variable "f" before firing up the ajax call to your controller. 🙂