2012-09-13 29 views
1

搜尋Drupal社區網頁搜索一個看似簡單的問題的答案的時間到目前爲止沒有結果,所以希望你能幫上忙!Drupal 6 - 如何實現(CCK)類型的「nodereference_autocomplete」的表單元素?

任何人都可以描述如何在自定義窗體中使用FAPI實現類型爲'nodereference_autocomplete'的輸入元素?對於外行人來說,這是一個AJAX修飾的文本字段,它在CCK模塊提供的匹配引用節點的字段上自動完成。我想在我自己的Drupal 6模塊中利用這個功能。

提交的值必須是被引用節點的nid。此外,如果將自動完成路徑約束爲僅包含「文章」和「博文」類型的節點,則會非常感謝。

感謝您對這個最基本的問題的幫助!

回答

5

我相信由於您不直接使用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); 
    } 
} 
+0

感謝您的幫助!編寫我自己的自動完成回調,就像你提供的,就是我最終做的。很棒! –

相關問題