具有自动完成功能的自定义字段

时间:2012-09-06 19:47:21

标签: drupal-7

我正在尝试构建自己的节点引用自定义字段 - 我知道有几个项目已经这样做了,我正在构建这个以便学习...:)

我的问题是自动完成路径,它没有被触发,我检查了noderefcreate项目并根据该项目实现了我的解决方案。但是仍然;检查萤火虫时没有触发任何东西。

这是我的代码:

function nodereference_field_widget_info() {
  return array(
    'nodereference_nodereference_form' => array(
      'label' => t('Node Reference Form'),
      'field types' => array('nodereference'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
      'settings' => array(
        'autocomplete_match' => 'contains',
        'autocomplete_path' => 'nodereference/autocomplete',
      ),
    ),
  );
}

function nodereference_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  if ($instance['widget']['type'] == 'nodereference_nodereference_form') {
    $widget = $instance['widget'];
    $settings = $widget['settings'];

    $element += array(
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]['nid']) ? $items[$delta]['nid'] : NULL,
      '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'],
    );
  }

  return array('nid' => $element);
}

1 个答案:

答案 0 :(得分:0)

您需要定义自动竞争将采取建议的方法。 可以这样做:

/**
 * implements hook_menu
 */
function your_module_name_menu() {
  $items['master_place/autocomplete'] = array(
    'page callback' => '_your_module_name_autocomplete',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

/**
 * Auto complete method implementation
 * @param $string
 */
function _your_module_name_autocomplete($string) {
  $matches = array();

  // Some fantasy DB table which holds cities
  $query = db_select('target_db_table', 'c');

  // Select rows that match the string
  $return = $query
    ->fields('c', array('target_column'))
    ->condition('c.target_column', '%' . 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);
}