Drupal 8: Load current entity from controller dynamically *updated*

Today I'd like to discuss a little Drupal 8 snippet to dynamically load an entity from the controller by the current path.

This acts a bit like a Drupal 8 replacement for Drupal 7's menu_get_object().

Use case / example:

We had to provide information on template level about the currently loaded (so to say "main") entity. What we mainly wanted to know was the entity type and bundle to add them as body class.

As we found out Drupal 8 offers the node object in

  1. hook_preprocess_page($variables){...}

  1. $variables['node']

but not for other entity types like user oder commerce_product which is a bit inconsistent and broke our before simple node logic for other entity types. But we also needed information for other entity types.

Example implementation in HOOK_preprocess_page

So we decided to extend our hook_preprocess_page by a more generic logic which returns the currently loaded entity information (by controller) or null if the current page is no entity page:

  1. function MYTHEME_preprocess_page(&$variables)
  2. {
  3.   // Provide information about the currently loaded page / Entity
  4.   // Default (and for non-entity pages):
  5.   $variables['entity_type'] = null; // Null on system pages
  6.   $variables['bundle'] = null; // Null on system pages
  7.   $variables['entity'] = null; // TODO - load from controller!
  8.   // Get information about the currently loaded entitiy from the controller (if it is an entity):
  9.   $routeParameters = \Drupal::routeMatch()->getParameters();
  10.   if ($routeParameters->count() > 0) {
  11.     // We use the first parameter as indicator for the entity type to load (node,user,commerce_product, ...)
  12.     $entityTypeIndicator = \Drupal::routeMatch()->getParameters()->keys()[0];
  13.     $entity = \Drupal::routeMatch()->getParameter($entityTypeIndicator);
  14.     if (is_object($entity) && $entity instanceof \Drupal\Core\Entity\ContentEntityInterface) {
  15.       $variables['entity_type'] = $entity->getEntityTypeId();
  16.       $variables['bundle'] = $entity->bundle();
  17.       $variables['entity'] = $entity;
  18.     }
  19.   }

Of course this logic also works in other places / modules etc. outside of HOOK_preprocess_page():

  1.   // Get information about the currently loaded entitiy from the controller (if it is an entity):
  2.   $routeParameters = \Drupal::routeMatch()->getParameters();
  3.   if ($routeParameters->count() > 0) {
  4.     // We use the first parameter as dynamic indicator for the entity type to load (node,user,commerce_product, ...)
  5.     $entityTypeIndicator = \Drupal::routeMatch()->getParameters()->keys()[0];
  6.     $entity = \Drupal::routeMatch()->getParameter($entityTypeIndicator);
  7.     if (is_object($entity) && $entity instanceof \Drupal\Core\Entity\ContentEntityInterface) {
  8.       // $entity is the currently loaded entity here.
  9.     }
  10.   }


I decided to write a different helper function based on comment #1 which requires less function calls and might have better performance:

  1. /**
  2.  * Helper function to return the currently loaded entity from the URL (controller).
  3.  * Returns NULL if the currently loaded page is no entity.
  4.  *
  5.  * @return \Drupal\Core\Entity\EntityInterface
  6.  */
  7. function _get_current_controller_entity()
  8. {
  9.   $currentRouteParameters = \Drupal::routeMatch()->getParameters();
  10.   foreach ($currentRouteParameters as $param) {
  11.     if ($param instanceof \Drupal\Core\Entity\EntityInterface) {
  12.       $entity = $param;
  13.       return $entity;
  14.     }
  15.   }
  16.   return NULL;
  17. }

Special thanks to @mxh for his idea!

Disclaimer: This is a proof-of-concept implementation and may fail in cases where for example the first parameter of the controller isn't the right parameter for our function. Eventually the allowed entity types / parameters should be whitelisted.

So what do you think? Was this helpful for you? Do you have improvements for my implementation?


Possible alternative?

I just found this possible alternative in a comment from @mxh here: https://www.drupal.org/forum/support/module-development-and-code-questio...

  1. $entities = [];
  2. foreach (\Drupal::routeMatch()->getParameters() as $param) {
  3.   if ($param instanceof \Drupal\Core\Entity\EntityInterface) {
  4.     $entities[] = $param;
  5.   }
  6. }

did someone test this? You could also break after the first entity matches. It would safe some lines of code...

Post new comment

The content of this field is kept private and will not be shown publicly.

More information about formatting options