简体   繁体   中英

How to make auto complete form in cakephp?

I am trying to make an auto complete function in CakePHP but did not succeed. I tried the following code.

public function find() {

    if ($this->request->is('ajax')) {

        $this->autoRender = false;            
        $country_name = $this->request->data['Country']['name'];            
        $results = $this->Country->find('all', array(
                                       'conditions' => array('Country.name LIKE ' => '%'                            . $country_name . '%'),
                                       'recursive'  => -1
                                       ));

        foreach($results as $result) {
                echo $result['Country']['name'] . "\n";
        }

        echo json_encode($results);

   } 

}

// Form and jquery

 <?php
        echo $this->Form->create('Country', array('action' => 'find'));
        echo $this->Form->input('name',array('id' => 'Autocomplete')); 
        echo $this->Form->submit();
        echo $this->Form->end();
    ?>
    <script type="text/javascript">
        $(document).ready(function($){
        $('#Autocomplete').autocomplete({
        source:'/countries/find', 
        minLength:2
     });
   });
    </script>     
       foreach($results as $result) {
            echo $result['Country']['name'] . "\n";
    }

Breaks your JSON structure.

Keep in mind that autocomplete by default expects "label" and value keys in your JSON table, so all the script should do after fetching DB records is:

    $resultArr = array();
    foreach($results as $result) {
            $resultArr[] = array('label' =>$result['Country']['name'] , 'value' => $result['Country']['name'] );
    }

    echo json_encode($resultArr);
    exit(); // may not be necessary, just make sure the view is not rendered

Also, I would create the URL to your datasource in the jQuery setup by

source:'<?=$this->Html->url(array("controller" => "countries","action"=> "find")); ?>',

And try to comment-out (just to make sure if the condition is not met by the request when autocomplete makes its call)

if ($this->request->is('ajax')) {

condition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM