1

I would like to attach a specific library using a taxonomy term to a content type with a specific field that is not empty. The following is not working:

function lehigh_preprocess_page(&$variables) {
// Via taxonomy term: If the landing page is a node and has taxonomy 
via a field named field_taxonomy
$current_route = \Drupal::routeMatch();
$node = $current_route->getParameter('node');
$target_taxonomy_id = 123;
   if ($node->getType() === 'standard_content_page') && $node->hasField('field_section') && !$node->get('field_section')->isEmpty()) {
     if ($node->get('field_section')->referencedEntities()[0]->id() == $target_taxonomy_id) {
     $variables['#attached']['library'][] = 'lehigh/financialaid';
}
}
}
  • 2
    Well you need to learn to debug. Basically figure out what "if statement" is failing to pass. – No Sssweat Oct 31 at 1:04
  • 1
    Check the route name, otherwise you get an error when you use getType() on a route parameter which doesn't exist or is of the wrong type. See for example drupal.stackexchange.com/a/285224/47547 – 4k4 Oct 31 at 12:23
  • 1
    Welcome to Drupal Answers! So far, you stated facts, but you didn't ask any explicit question. If the implicit question is Why doesn't my code work? that is a too broad question. – kiamlaluno Oct 31 at 15:55
0

Try the following , and don't forget to clear the cache

function lehigh_preprocess_page(&$variables) {
    $current_route = \Drupal::routeMatch();
    $node = $current_route->getParameter('node');
    $target_taxonomy_id = 123;
    if (isset($node) && $node->getType() == 'standard_content_page' 
        && $node->hasField('field_section') 
        && !$node->get('field_section')->isEmpty()) {
        if ($node->get('field_section')->referencedEntities()[0]->id() == $target_taxonomy_id) {
            $variables['#attached']['library'][] = 'lehigh/financialaid';
        }
    }
}
  • 1
    There isn't the need of using all that code to get the node object, since that is already available in $variables['node'], if the page is a node page. – kiamlaluno Oct 31 at 16:04
  • 1
    The isset($node) is good, because we're in preprocess_page: Not every page is a node and a non-node-page would crash on $node->getType(). But even some node routes (e.g. preview) don't do parameter upcasting, so better use $node instanceof \Drupal\node\NodeInterface instead – Hudri Oct 31 at 16:12
  • @Hudri I'm agree with you. did this solution work for you? – Yusef Oct 31 at 16:12
  • 1
    @YusefMohamadi I'm not the questioner, but I had wasted some hours due (int) $current_route->getParameter('node') ;-) – Hudri Oct 31 at 16:15
  • @Hudri, sorry I miss read. hundri, hunter :) – Yusef Oct 31 at 16:22

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