In Drupal 7, and before this patch got committed, it was effectively impossible to set an entity-specific attribute (e.g. one that includes its ID) on all entities (i.e. across all entity types: node, taxonomy term, custom block, and so on). You could not even set a foo="bar"
attribute on all entities!
We solved this by having attributes set in hook_entity_view_alter()
be inherited (merged) with existing attributes.
(In fact, we solved this generically: in template_preprocess()
, the basic preprocessing function that runs for all rendered things, we made sure that if we're rendering a so-called render element, and if that render element has any #attributes
set, then we merge those with the attributes that will be passed to the template or theme function: with $variable['attributes']
).
Drupal 7
/**
* Implements hook_preprocess_HOOK() for node.tpl.php.
*/
function edit_preprocess_node(&$variables) {
$node = $variables['elements']['#node'];
$variables['attributes']['data-edit-entity'] = 'node/' . $node->nid;
}
/**
* Implements hook_preprocess_HOOK() for taxonomy-term.tpl.php.
*/
function edit_preprocess_taxonomy_term(&$variables) {
$term = $variables['elements']['#term'];
$variables['attributes']['data-edit-entity'] = 'taxonomy_term/' . $term->id();
}
Drupal 8
/**
* Implements hook_entity_view_alter().
*/
function edit_entity_view_alter(&$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
$build['#attributes']['data-edit-entity'] = $entity->entityType() . '/' . $entity->id();
}