Tuesday, April 3, 2012

Using CJuiAutoComplete in yii framework

In the version 1.1.3 yii CAutoComplete was deprecated, so for better result you should consider using CJuiAutoComplete to make autocomplete in yii framework.

To use this widget is more easy to use but with the multiple selections of CJuiAutoComplete maybe you should have to implements more javascript functions.

Let's take a look how to make CJuiAutoComplete with multiple selection enabled. Assume you have code in the article in views article /protected/views/article/_form.php. And I have table with just only 2 fields : id_tag and name



<div class="row">
  <?php echo CHtml::script("
      function split(val) {
       return val.split(/,\s*/);
      }
      function extractLast(term) {
       return split(term).pop();
      }
    ")?>
  <?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
    'model'=>$model,
    'attribute'=>'tag',
    'source'=>"js:function(request, response) {
       $.getJSON('".$this->createUrl('suggest')."', {
         term: extractLast(request.term)
       }, response);
       }",
    'options'=>array(
      'delay'=>300,
      'minLength'=>2,
      'showAnim'=>'fold',
      'select'=>"js:function(event, ui) {
          var terms = split(this.value);
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push('');
          this.value = terms.join(', ');
          return false;
        }"
    ),
    'htmlOptions'=>array(
      'size'=>'40'
    ),
   ));?>
  <?php echo $form->labelEx($model,'tag'); ?>
  <?php echo $form->hiddenField($model,'tag',array('rows'=>6, 'cols'=>50)); ?>
  <?php echo $form->error($model,'tag'); ?>
 </div>

and then the action in your /protected/controller/ArticleController.php the sample of action code :

public function actionSuggest(){
  if (Yii::app()->request->isAjaxRequest && isset($_GET['term'])) {
   $models = Tag::model()->suggestTag($_GET['term']);
   $result = array();
   foreach ($models as $m)
    $result[] = array(
      'label' => $m->name,
      'value' => $m->name,
      'id' => $m->id_tag,
    );
  
   echo CJSON::encode($result);
  }
 }
Don't forget to add rules to suggest in the rules()..
And then the code in the /protected/models/ Tag.php
public function suggestTag($keyword){
  $tags=$this->findAll(array(
    'condition'=>'nama LIKE :keyword',
    'params'=>array(
      ':keyword'=>'%'.strtr($keyword,array('%'=>'\%', '_'=>'\_', '\\'=>'\\\\')).'%',
    )
  ));
  return $tags;
 }

That's the sample of using CJuiAutoComplete

3 comments:

  1. Thanks alot. I've been trying to get this thing working and I did, thanks to you. Great man!

    ReplyDelete
  2. Dude. This saved my cookies. Thank you for posting it!

    ReplyDelete