1

with a custom module, in drupal 8, how can I test whether I am on a node entity or not, when i browse to that page?

If I do this $node = \Drupal::routeMatch()->getParameter('node'); I get an error if i'm not on a node.

  • What is it you are trying to do? By limiting your module to nodes, you eliminate it from being usable on other entity types - which may be ok, but there may be a better way to go about it – Jaypan Apr 7 '17 at 13:19
  • I need to get a taxonomy term which will only be available to nodes. I already know how to get the taxonomy term if i'm on a node – Diana Apr 7 '17 at 13:20
1

Getting the route parameter is not a problem, this returns NULL if the route parameter is not present. But you have to check the node is not NULL, before using it:

if ($node = \Drupal::routeMatch()->getParameter('node')) {
  $value = $node->field_name->value;
}
0

You can do:

if(\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical'){
 //Do what you want.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.