Making an entity fieldable
Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites
This documentation needs work. See "Help improve this page" in the sidebar.
The starting point for making an entity fieldable is the hook_entity_info
.
Here is an example implementation from the user entity (defined in the User module).
/**
* Implements hook_entity_info().
*/
function user_entity_info() {
$return = array(
'user' => array(
'label' => t('User'),
'controller class' => 'UserController',
'base table' => 'users',
'uri callback' => 'user_uri',
'label callback' => 'format_username',
'fieldable' => TRUE,
// $user->language is only the preferred user language for the user
// interface textual elements. As it is not necessarily related to the
// language assigned to fields, we do not define it as the entity language
// key.
'entity keys' => array(
'id' => 'uid',
),
'bundles' => array(
'user' => array(
'label' => t('User'),
'admin' => array(
'path' => 'admin/config/people/accounts',
'access arguments' => array('administer users'),
),
),
),
'view modes' => array(
'full' => array(
'label' => t('User account'),
'custom settings' => FALSE,
),
),
),
);
return $return;
}
For information on this array structure as well as more possible keys be sure to read the API reference.
Most importantly, the 'fieldable'
property defined inside a hook_entity_info
implementation needs to be set to TRUE
. In the words of the Field Attach API:
hook_entity_info() is the central place for entity types to define if and how Field API should operate on their entity objects. Notably, the 'fieldable' property needs to be set to TRUE.
At this point, your entity is fieldable.
Some points to consider:
- Setting the (optional)
'bundles'
property is an important as well as useful step; it allows you to define an existing menu router item where the Field UI module will automatically provide the field management UI used for adding fields to our entity bundle and managing their display views. - If the
'bundles'
property is not set, your entity is still fieldable, even though the Field UI module is not going to provide tabs for managing fields. This can still be done programmatically and the entity type is considered to expose a single bundle with all entities sharing the same collection of fields.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion