1
votes

Since CakePHP 1.3, the Ajax helper has been deprecated, one cannot user $ajax->Autocomplete..

I use Cake 2.0, and wish to implement dynamic autocomplete( dynamic table, dynamic field) it seems impossible with current tutorials available.

What is closest alternative to $ajax->autoComplete in cakephp 2.0?

1
what do you mean by dynamic autocomplete (dynamic table and fields)?gautamlakum
You can also try this helper: cakephp.4uk.plMelissa L

1 Answers

6
votes

One method I've used is to create an Autocomplete Controller (or better yet build it as a plugin), with a method similar to this:

class AutocompleteController extends AppController {

    public function fetch($model, $field, $query) {

       $this->loadModel($model);

       $results = $this->$model->find('all', array(
           'conditions'=>array(
               $model . "." . $field . " LIKE '%" . $query . "%'"
           )
       ));

       $this->set(compact('results');

    }

}

/Views/Autocomplete/fetch.ctp:

<?php echo json_encode($results); ?>

To fetch the data, you would use the following URL in your javascript:

/autocomplete/fetch/name_of_your_model/name_of_your_field/string_to_look_for

e.g.

/autocomplete/fetch/User/name/rich

Edit:

Another alternative is to create an autocomplete method in app controller:

public function autocomplete($field, $query) {

   $model = $this->{$this->$modelClass}->alias;

   $results = $this->$model->find('all', array(
       'conditions'=>array(
           $model . "." . $field . " LIKE '%" . $query . "%'"
       )
   ));

   $this->set(compact('results');

}

And is called with a url like this:

/users/autocomplete/name/rich

which will return all users with an email address LIKE '%rich%'