Drupal FAPI错误;无法创建对字符串偏移或来自重载对象的引用

时间:2012-09-13 21:57:39

标签: php drupal drupal-7

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

我已经成功地完成了这项任务,但现在每当我提交注册表单时,我都会得到一个空白页面,并且此错误会显示在日志中;

  

PHP致命错误:无法创建对字符串偏移的引用,也不能重载   第6448行/var/www/html/drupal/includes/common.inc中的对象,   referer:http:// [...] / drupal /?q = user / register

我现在找不到这个主题,但是当我最初搜索这个问题时,我在某处读到这个问题通常是从属性键中添加或遗漏了'#'符号。因为没有#符号,它会将该属性的值视为子元素,从而将数组视为一个元素。或者沿着这些方向的东西,但经过仔细检查后,似乎我正在使用的所有属性都应该像我所说的那样。

这是代码,有人知道我做错了吗?

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

1 个答案:

答案 0 :(得分: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';