cakephp オートコンプリート機能 (DBからデータ取得)
TestAAAのページからTestBBBのデータベースの値を取得して、
オートコンプリート機能を実装。
まずは、Viewを作成
1.フォームの追加
<?php echo $this->Form->input('name', array(
'type' => 'text',
'id' => 'autocomplete',
)); ?>
2.Javascriptの読み込み
<script type="text/javascript">
$(function(){
$('#autocomplete').autocomplete({
source: 'http://localhost/cakephp/testAAA/autocomplete',
autoFocus: true,
//delay: 500,
//minLength: 2
});
})
</script>
下記のURLから値を拾う!
http://localhost/cakephp/testAAA/autocomplete
3.コントローラーの作成
上記のURLにjsonで値を渡す。
public function autocomplete(){
$this->loadModel('testBBB');
$field = 'name';
$term = $this->params['url']['term'];
// 入力値 無:全てのデータの中から10件返す。
// 入力値 有:入力値を含むデータを10件返す
$condition = array();
if(!empty($term)){
$condition = array('testBBB.'.$field.' like' => "%".$term."%");
}
$query = array(
'fields' => array($field),
'conditions' => $condition,
'limit' => 10,
'order' => array('testBBB.'.$field => 'ASC'),
'group' => $field,
);
$data = array();
$items = $this->testBBB->find('all', $query);
foreach ($items as $item) {
$cnt = array_push($data, $item['testBBB'][$field]);
}
// JSONデータのみを返す
$this->viewClass = 'Json';
$this->set(compact('data'));
$this->set('_serialize', 'data');
}
これでいけた!!!!!
3日間もハマってました。。。笑