Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create and instantiate a new custom field in hook_install() of the module that declares that custom field?

My module defines a custom field type with hook_field_info(). In hook_install() of this module, I am trying to create new fields and instances of this custom field type:

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);
  }
}

The code crashes at 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).

What's wrong?

like image 650
Dmitry Minkovsky Avatar asked Jan 16 '23 18:01

Dmitry Minkovsky


1 Answers

You are trying to enable a module that defines field types and attempts to use those same field types in its hook_install(), before it's enabled. Drupal's field info cache is not rebuilt before hook_install() is run, so Drupal does not know about the field types in your module when you're trying to create your field.

To get around this, manually rebuild the field info cache by calling field_info_cache_clear() before 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);
}
like image 126
Dmitry Minkovsky Avatar answered Apr 28 '23 00:04

Dmitry Minkovsky