我相信由於您不直接使用CCK,您需要在模擬CCK行爲的自定義模塊中編寫一些代碼。您可以使用FAPI的自動完成功能。
你form_alter或形式定義代碼可能是這樣的:
$form['item'] = array(
'#title' => t('My autocomplete'),
'#type' => 'textfield',
'#autocomplete_path' => 'custom_node/autocomplete'
);
由於需要根據節點類型限制,您可能需要創建自己的自動完成回調也是如此。這看起來是這樣的:
function custom_node_autocomplete_menu() {
$items = array();
$items['custom_node/autocomplete'] = array(
'title' => '',
'page callback' => 'custom_node_autocomplete_callback',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function custom_node_autocomplete_callback($string = '') {
$matches = array();
if ($string) {
$result = db_query_range("SELECT title, nid FROM {node} WHERE type IN('article', 'blogpost') AND LOWER(title) LIKE LOWER('%s%%')", $string, 0, 5);
while ($data = db_fetch_object($result)) {
$matches[$data->title] = check_plain($data->title) . " [nid:" . $data->nid . "]";
}
}
print drupal_to_js($matches);
drupal_exit();
}
然後,你需要編寫代碼從提交的值中提取節點ID。以下是CCK使用的代碼:
preg_match('/^(?:\s*|(.*))?\[\s*nid\s*:\s*(\d+)\s*\]$/', $value, $matches);
if (!empty($matches)) {
// Explicit [nid:n].
list(, $title, $nid) = $matches;
if (!empty($title) && ($n = node_load($nid)) && trim($title) != trim($n->title)) {
form_error($element[$field_key], t('%name: title mismatch. Please check your selection.', array('%name' => t($field['widget']['label']))));
}
}
else {
// No explicit nid.
$reference = _nodereference_potential_references($field, $value, 'equals', NULL, 1);
if (empty($reference)) {
form_error($element[$field_key], t('%name: found no valid post with that title.', array('%name' => t($field['widget']['label']))));
}
else {
// TODO:
// the best thing would be to present the user with an additional form,
// allowing the user to choose between valid candidates with the same title
// ATM, we pick the first matching candidate...
$nid = key($reference);
}
}
感謝您的幫助!編寫我自己的自動完成回調,就像你提供的,就是我最終做的。很棒! –