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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With