如何在声明该自定义字段的模块的hook_install()中创建和实例化新的自定义字段?

时间:2012-08-20 22:02:47

标签: drupal drupal-7

我的模块使用hook_field_info()定义自定义字段类型。在此模块的hook_install()中,我正在尝试创建此自定义字段类型的新字段和实例:

function my_module_install() {

  if (!field_info_field('my_field')) {
    $field = array(
      'field_name' => 'my_field',
      'type' => 'custom_field_type',
      'cardinality' => 1
    );
    field_create_field($field);
  }
}

代码在field_create_field($field)处崩溃:

WD php: FieldException: Attempt to create a field of unknown type custom_field_type. in field_create_field() (line 110 of                                            [error]
/path/to/modules/field/field.crud.inc).
Cannot modify header information - headers already sent by (output started at /path/to/drush/includes/output.inc:37) bootstrap.inc:1255                             [warning]
FieldException: Attempt to create a field of unknown type <em class="placeholder">custom_field_type</em>. in field_create_field() (line 110 of /path/to/modules/field/field.crud.inc).

出了什么问题?

1 个答案:

答案 0 :(得分:9)

您正在尝试启用定义字段类型的模块,并尝试在其hook_install()中使用这些字段类型,然后再启用它们。运行hook_install()之前不会重建Drupal的字段信息缓存,因此当您尝试创建字段时,Drupal不知道模块中的字段类型。

要解决此问题,请在field_info_cache_clear()之前调用field_create_field($field)来手动重建字段信息缓存:

if (!field_info_field('my_field')) {
  field_info_cache_clear();

  $field = array(
    'field_name' => 'my_field',
    'type' => 'custom_field_type',
    'cardinality' => 1
  );
  field_create_field($field);
}