A simple action for CJuiAutoComplete

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#1)next (#3) »

Scenario

More or less I use auto-complete field for a form. CJuiAutoComplete is a yii widget for this purposes. The common use case is to make an ajax request and retrieve a list from the database. So in this case you have to write a controller action to return you a json encoded list. What if I had a generic action to do this work for me?

Implementation

This is a class that extends CAction to do the work for me.

<?php
class EAutoCompleteAction extends CAction
{
    public $model;
    public $attribute;
    private $results = array();

    public function run()
    {
        if(isset($this->model) && isset($this->attribute)) {
            $criteria = new CDbCriteria();
            $criteria->compare($this->attribute, $_GET['term'], true);
            $model = new $this->model;
            foreach($model->findAll($criteria) as $m)
            {
                $this->results[] = $m->{$this->attribute};
            }
                
        }
        echo CJSON::encode($this->results);
    }
}
?>

Simple as that. I have placed this action in my extension folder like:

./webapp/protected/extensions/EAutoCompleteAction.php
Use

And in my controller I declare this action in the public actions function:

Declare action in controller
class MyController extends CController
{
  ...
  public function actions()
  {
    return array(
      'aclist'=>array(
        'class'=>'application.extensions.EAutoCompleteAction',
        'model'=>'My', //My model's class name
        'attribute'=>'my_name', //The attribute of the model i will search
      ),
    );
  }
  ...
}
Use in CJuiAutoComplete widget

So i have a form view like: ~~~ ./webapp/protected/views/my/_form.php ~~~ I initialize my widget there like.

<?php 
  $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
      'attribute'=>'my_name',
        'model'=>$model,
        'sourceUrl'=>array('my/aclist'),
        'options'=>array(
          'minLength'=>'3',
        ),
        'htmlOptions'=>array(
          'size'=>45,
          'maxlength'=>45,
        ),
  )); ?>

And I am done. Now I can use this CAction in whatever Controller I want for whatever model I want and get quick results.

15 1
19 followers
Viewed: 49 047 times
Version: Unknown (update)
Category: Tips
Written by: tydeas_dr
Last updated by: Thiago Souza
Created on: Mar 23, 2011
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles