花了几个小时在Drupal社区页面上寻找一个看似简单的问题的答案,到目前为止还没有得到任何结果,所以希望您能提供帮助!
有谁能描述一下如何在自定义表单中使用FAPI实现'nodereference_autocomplete‘类型的输入元素吗?对于外行来说,这是一个AJAX修饰的文本字段,它会在CCK模块提供的匹配引用节点的字段上自动完成。我想在我自己的Drupal6模块中利用这个功能。
提交的值必须是被引用节点的nid。此外,将自动完成路径限制为仅包含“文章”和“博客帖子”类型的节点的说明将是最受欢迎的。
感谢您在这个最基本的问题上的帮助!
发布于 2012-10-26 06:49:16
我认为,由于您没有直接使用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);
}
}https://stackoverflow.com/questions/12398096
复制相似问题