Create a custom field for Drupal 7 by using hook_field_extra_fields()
by adding a little bit of code to a custom module. This method is intended for display and will provide you with a custom field for the display of a node or entity.
Alternatively, you may also want to check out the Computed Field module. Computed Field will also give you the ability to create a custom display field using tokens without the need to write any custom code.
Benefits of using hook_field_extra_fields()
is that you will not depend on an additional contributed module, which would be subject to updates or potential security risk if updates go unchecked. Additionally, you have more flexibility with what can be available to your custom field.
To start out, you’ll need to have either an existing custom module or create a new one for your code. Then we’ll want to use hook_field_extra_fields()
and hook_node_view()
for the example below my custom module will be aptly named “example_module”. You will need to replace “example_module” with the name of your module.
In the example.module file, we’ll add the following to example_module.module:
/**
* Implements hook_field_extra_fields().
*/
function example_module_field_extra_fields() {
$extra['node']['article']['display']['custom_field'] = array(
'label' => t('Custom Field'),
'description' => t('Example custom field'),
'weight' => 0,
);
return $extra;
}
/**
* Implements hook_node_view().
*/
function example_module_node_view($node, $view_mode, $langcode) {
// Only add to the "full" page display on "article" node type.
if ($view_mode == 'full' && $node->type == 'article') {
$node->content['custom_field'] = array(
'#markup' => '<p>This is my custom field</p>',
);
}
}
For this example, the code above will add a new field to the “Article” content type that simply reads “This is my custom field”.
The weight of this field can be configured from display options for the Article Content type.
Alternatively, you may also want to place your field on a different entity, rather than a content type. In that case, you’ll want to use hook_entity_view()
instead of hook_node_view()
.