5

我正在尝试按照本教程的内容向我的用户注册页面上的几个文本字段添加一些自定义自动完成功能;http://drupal.org/node/854216

我已经能够成功地做到这一点,但是现在每当我提交注册表单时,我都会得到一个空白页,并且此错误会显示在日志中;

PHP 致命错误:无法在第 6448 行的 /var/www/html/drupal/includes/common.inc 中创建对字符串偏移量或重载对象的引用,引用者:http://[...]/drupal/?q =用户/注册

我现在找不到这个话题,但是当我最初在谷歌上搜索这个问题时,我在某处读到这个问题通常是属性键中添加或遗漏了“#”符号。因为没有 # 符号,它将该属性的值视为子属性,因此是数组。或者类似的东西,但是在仔细检查之后,我使用的所有属性似乎都应该是我放置的。

这是代码,有谁知道我做错了什么?

function gtx_alterations_menu() {
  $items = array();
  $items['city/autocomplete'] = array(
    'page callback' => 'city_autocomplete',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
  return $items;
}

function gtx_alterations_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['field_city_of_residence']['#type'] = 'textfield';
    $form['field_city_of_residence']['#title'] = t('City of Residence');
    $form['field_city_of_residence']['#autocomplete_path'] = 'city/autocomplete';
    $form['field_headquarters_location']['#type'] = 'textfield';
    $form['field_headquarters_location']['#title'] = t('Headquarters Location');
    $form['field_headquarters_location']['#autocomplete_path'] = 'city/autocomplete';
  }
}

function city_autocomplete($string = '') {
  $cities = array();
  $locations = array();
  $results = file_get_contents('http://graph.facebook.com/search?q='.urlencode($string).'&type=adcity');

  $results = preg_replace('/\\\\u0*([0-9a-fA-F]{1,5})/', '&#x\1;', $results);

  preg_match_all('/"name":"[^,]+/', $results, $cities);
  preg_match_all('/"subtext":".+?,[^"]+/', $results, $locations);

  $final = array();

  foreach ($cities[0] as $key => $value) {
    $value = substr($value, 8);
    $subtext = substr($locations[0][$key], 11);
    $result = $value . ', ' . $subtext;

    $final[$result] = $result;
  }

  drupal_json_output($final);
}

我尝试过的一些事情

当试图缩小问题范围时,我决定注释掉这两行;

$form['field_city_of_residence']['#autocomplete_path'] = 'city/autocomplete';
$form['field_headquarters_location']['#autocomplete_path'] = 'city/autocomplete';

删除错误,但这自然意味着自动完成功能也被禁用。


另外将 city_autocomplete($string) 的内容替换为

drupal_json_output(array('test' => 'test'));

不能解决错误,这意味着问题不在该函数中。


从这两行中删除 # 符号

$form['field_city_of_residence']['#autocomplete_path'] = 'city/autocomplete';
$form['field_headquarters_location']['#autocomplete_path'] = 'city/autocomplete';

导致上一个错误被这个错误替换,

Unsupported operand types in /var/www/html/drupal/includes/form.inc on line 1755
4

1 回答 1

5

Drupal 7 中的字段表单有点混乱,看看Why is hook_form_alter so messy in d7? 有点崩溃。

可以说实际的 HTML 元素(您要更改其值的元素)在数组的更深处找到,例如

$form['field_city_of_residence'][LANGUAGE_NONE][0]['value']['#type'] = 'textfield';
$form['field_city_of_residence'][LANGUAGE_NONE][0]['value']['#title'] = t('City of Residence');
$form['field_city_of_residence'][LANGUAGE_NONE][0]['value']['#autocomplete_path'] = 'city/autocomplete';
于 2012-09-13T23:43:01.033 回答