2014-09-18 22 views
0

我想在CakePHP中做一個自動完成的函數,但沒有成功。我試了下面的代碼。如何在cakephp中自動完成表單?

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); 

    } 

} 

//形式和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>  

回答

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

傷了你的JSON結構。

請記住,自動完成默認情況下,預計「標籤」,並在你的JSON表值鍵,因此所有的腳本讀取數據庫記錄後應該做的是:

$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 

另外,我想創建網址你在jQuery的設置數據源通過

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

並嘗試註釋掉(只是爲了確保,如果條件沒有被滿足的要求自動完成使得其呼叫時)

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

條件

+0

我試過你的代碼,但它沒有任何效果。 – 2014-09-19 12:31:00

+0

我在控制器代碼中添加了$ country_name = $ this-> request-> query('term'),現在它正在工作。感謝您的幫助。 – 2014-09-20 03:06:53