0

I'm currently trying to set up a simple LMS and have already defined a content type course that contains a term reference field accesstags, which I would like to use for defining view permissions. I.e. the field accesstags will contain multiple terms that will be linked to roles that should have access to the node in question.

To make a long story short: I have created a custom module that contains the function hook_entity_view_mode_alter and I would like to check, whether the term reference field accesstags contains the term "subscription":

function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  ...
  if (in_array('subscription', ?????)) {
    ... allow access ...
  }
  ...
}

However, I'm not sure what to put at the spot that I marked with "?????". I know that I can construct the array of referenced terms by using $entity->get('field_accesstags')->referencedEntities()... but this array then contains the whole structure, whereas I only need the array of labels.

Is there an easy way for getting this array? Maybe even a built-in function?

Any help would be much appreciated.

3
  • 1
    Yes, this array of terms is a good starting point. You'll find the label in $term->getName() when iterating the array, for example with array_filter().
    – 4uk4
    Nov 17, 2018 at 9:14
  • Thanks, that was exactly the help that I needed. I ended up using array_map() in combination with a small helper function that called getName() on the elements of the array built with referencedEntities(). Much appreciated. (Would you like to post your comment as an answer so that I can accept it?)
    – Marcus C.
    Nov 17, 2018 at 14:09
  • You can put the final code in an answer.
    – 4uk4
    Nov 17, 2018 at 15:03

1 Answer 1

1

Following @4k4's suggestion to post the final code as an answer myself... here's the code that I'm now using and that seems to work well...

First of all, I defined a simple helper function:

function getTermName($term) {
  return($term->getName());
}

This allowed me to extend my code (see my original question above):

function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  ...
  $accesstags = array_map("getTermName", $entity->get('field_accesstags')->referencedEntities());
  if (in_array('subscription', $accesstags)) {
    ... allow access ...
  }
  ...
}

I'm still wondering, if there is a simpler way (without having to iterate over the array of terms), but for now the solution works well. Thanks again for your help, @4k4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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