drupal 自定义表单调用autocomplete主标签实现方法

代码如下: 
<php 
function module_name_form() { 
$form = array(); 
$form['city'] = array( 
'#title' => t('City'), 
'#type' => 'textfield', 
'#autocomplete_path' => 'example/autocomplete',//--调用的路径 
); 
$form['submit'] = array( 
'#type' => 'submit', 
'#value' => 'Save', 
); 
return $form; 

//--定义路径 
function module_name_menu() { 
$items['example/autocomplete'] = array( 
'page callback' => '_module_name_autocomplete', //--调用数据 
'access arguments' => array('access example autocomplete'), 
'type' => MENU_CALLBACK 
); 
return $items; 

//--从数据库读取返回数据 
function _module_name_autocomplete($string) { 
$matches = array(); 
// Some fantasy DB table which holds cities 
$query = db_select('cities', 'c'); 
// Select rows that match the string 
$return = $query 
->fields('c', array('city')) 
->condition('c.city', '%' . db_like($string) . '%', 'LIKE') 
->range(0, 10) 
->execute(); 
// add matches to $matches 
foreach ($return as $row) { 
$matches[$row->city] = check_plain($row->city); 

// return for JS 
drupal_json_output($matches); //--json格式返回 

?> 

posted @ 2016-12-27 18:02  鼎峰Bruce  阅读(311)  评论(0编辑  收藏  举报