数据查询自动完成属性 #autocomplete_path

-- Submitted by Admin on Thu, 05/13/2010 - 21:00

查询数据自动完成(比如 free tags)或搜索内容自动完成(比如drupal api的自动搜索),这样的效果省时又省力!所以让我们来学会它并在项目中多用吧!

一、表单中定义 #autocomplete_path 属性

$form['user_select'] = array(
  '#type' => 'textfield',
  '#autocomplete_path' => 'user/autocomplete',
);

二、定义一个#autocomplete_path

$items['user/autocomplete'] = array(
    'page callback' => 'user_autocomplete',
    'type' => MENU_CALLBACK
  );

三、定义调用路径的回调函数

<?php
function user_autocomplete($string){
 
$matches = array();
  if (
$string) {
   
$result = db_query_range("SELECT n.nid,n.title FROM {node} n WHERE n.title LIKE('%s%%') AND n.type='%s'", $string,'user', 0, 20);
    while (
$row = db_fetch_object($result)) {
     
$matches[$row->title .' [nid:'. $row->nid .']'] = check_plain($row->title);
    }
  }
  print
drupal_to_js($matches);
}
?>

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Allowed HTML tags: <a> <em> <strong> <code> <cite> <ul> <ol> <li> <dl> <dt> <dd> <img> <ebmed>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
3 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.