Displaying properties when viewing entities

Last updated on
14 October 2016

When an entity is viewed, the EntityAPIController calls the buildContent() method to assemble the entity information, entity's field data and invoke hooks to modify the entity information.

One way to display the entity's properties when viewing an entity is to use the EntityDefaultExtraFieldsController class. To use this class, you first need to add the 'extra fields controller class' to your entity_info declaration in your module file:

/**
 * Implements hook_entity_info().
 */
function mymodule_entity_info() {
  $entities['myentity'] = array(
    'metadata controller class' => 'MyEntityMetadataController',
    'controller class' => 'EntityAPIController',
    'extra fields controller class' => 'EntityDefaultExtraFieldsController',
    'admin ui' => array(
      'path' => 'myentity',
      'menu wildcard' => '%myentity',
      'controller class' => 'EntityDefaultUIController',
    ),
    ...
  );
  return $entities;
}

Next, you should define your property info. As noted in other documentation, you can either do this with a hook_entity_property_info() or by extending the EntityDefaultMetadataController class:

class MyEntityMetadataController extends EntityDefaultMetadataController {
  public function entityPropertyInfo() {
    $info = parent::entityPropertyInfo();
    $info[$this->type]['properties']['my_id'] = array(
      'label' => t('Custom ID'),
      'type' => 'integer',
      'description' => t('My Entity ID'),
      'schema field' => 'my_id',
      'setter callback' => 'entity_property_verbatim_set',
    );
    return $info;
  }
}

If you're using the EntityDefaultUIController (as in the first code section above) or a class that extends it, you should be done and any properties declared will appear when viewing your entity. If you are creating a custom menu, then you'll want to call entity_ui_entity_page_view as your page callback:

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items['myentity/%myentity'] = array(
    'page callback' => 'entity_ui_entity_page_view',
    'page arguments' => array(1),
    'load arguments' => array('myentity'),
    ...
  );
  return $items;
}