Drupal allows access to the currently loaded entity that is controlling the page. These are passed as parameters to the route and are then made available via the route object.
If you know that the entity in the current page is a node then you get get the node object using the route match service quite easily.
$node = \Drupal::routeMatch()->getParameter('node');
If you aren't sure what the type of entity is then you can use the route match service to find all of the parameters and match the once that is a type of entity.
$route = \Drupal::routeMatch();
$entity = NULL;
if ($route->getRouteObject()) {
foreach ($route->getParameters() as $name => $parameter) {
if ($parameter instanceof \Drupal\Core\Entity\EntityInterface) {
$entity = $parameter;
break;
}
}
}
The $entity variable here will now be the currently loaded entity object.
If you just want an entity of a particular type then you can also search for that object in the parameters list.
$route = \Drupal::routeMatch();
$entity = NULL;
if ($route->getRouteObject()) {
foreach ($route->getParameters() as $name => $parameter) {
if ($parameter instanceof \Drupal\taxonomy\TermInterface) {
$entity = $parameter;
break;
}
}
}
Add new comment