Tuesday, May 15, 2012

Yii CAutoComplete or autosuggestion to display one value and submit another

In your view file, embed the following code within your form:
    <?php
$this->widget('CAutoComplete',
          array(
                         //name of the html field that will be generated
              'model'=>$model,
               'attribute'=>'titile',
                         //replace controller/action with real ids
             'url'=>array('task/AutoCompleteLookup'),
             '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'=>2,
             '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'),

             'methodChain'=>".result(function(event,item){\$(\"#Task_titile\").val(item[1]);})",
             ));
    ?>
 In your controller, create a new action to handle AutoCompleteLookup queries
<?php

    public function actionAutoCompleteLookup()
    {
       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
            */
          $titile = $_GET['q'];
                    // this was set with the "max" attribute of the CAutoComplete widget
          $limit = min($_GET['limit'], 50);
          $criteria = new CDbCriteria;
          $criteria->condition = "titile LIKE :titile";
          $criteria->params = array(":titile"=>"%$titile%");
          $criteria->limit = $limit;
          $taskArray = Task::model()->findAll($criteria);
          $returnVal = '';
          foreach($taskArray as $usertask)
          {
             $returnVal .= $usertask->getAttribute('titile').'|'
                                         .$usertask->getAttribute('titile')."\n";
          }
          echo $returnVal;
       }
    }

?>


No comments:

Post a Comment