Created
April 22, 2011 10:35
-
-
Save junichi11/936425 to your computer and use it in GitHub Desktop.
CakePHP jQuery Ui Autocomplete Component (get data from DB)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* JqueryUiAutocomplete Component | |
* サーバー側にデータが要求されたときにDBからデータを取得 | |
* | |
* @author junichi11 | |
* | |
*/ | |
class JuAutocompleteComponent extends Object | |
{ | |
public $controller = null; | |
protected $_query = array( | |
'position' => 'center', | |
'limit' => 10, | |
'order' => 'ASC', | |
); | |
function __construct(){ | |
parent::__construct(); | |
} | |
function startup(&$controller){ | |
$this->controller =&$controller; | |
if(!empty($this->controller->autocomplete)){ | |
$this->_query = array_merge($this->_query, $this->controller->autocomplete); | |
} | |
} | |
/** | |
* Get data | |
* @param array $get GET送信で取得したデータ field, term | |
* @param array $whitelist アクセス可能なテーブルのフィールド | |
* @param string $model モデル名 | |
* @return array $data | |
*/ | |
function getData($model, $whitelist = array()){ | |
$model = ucfirst($model); | |
$this->model = $this->controller->$model; | |
$field = $this->controller->params['url']['field']; | |
$term = $this->controller->params['url']['term']; | |
if(!in_array($field, $whitelist)){ | |
return false; | |
} | |
$condition = array(); | |
$position = "%".$term."%"; | |
if($this->_query['position'] == 'center'){ | |
$position = "%".$term."%"; | |
}else if($this->_query['position'] == 'left'){ | |
$position = $term."%"; | |
}else if($this->_query['position'] == 'right'){ | |
$position = "%".$term; | |
} | |
if(!empty($term)){ | |
$condition = array($this->model->alias.'.'.$field.' like' => $position); | |
} | |
$query = array( | |
'fields' => array($field), | |
'conditions' => $condition, | |
'limit' => $this->_query['limit'], | |
'order' => array($this->model->alias.'.'.$field => $this->_query['order']), | |
'group' => $field, | |
); | |
$data = array(); | |
$items = $this->model->find('all', $query); | |
foreach ($items as $item) { | |
if(!empty($item[$this->model->alias][$field])){ | |
$cnt = array_push($data, $item[$this->model->alias][$field]); | |
} | |
} | |
return $data; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment