Using my theme file, I created a theme/template suggestion for taxonomies. I load a term object so I can know its vid. This was working and still works most the time. However, occasionally I get fatal errors. Which is a big deal. Similar to:

Fatal error: Class 'Term' not found in myTheme.theme on line 4.

I am not sure why the term class isn't found, and only sometimes? Any suggestions on how to prevent this error?

Most of the time rebuilding the cache would fix this but not always.


function myTheme_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
| improve this question | | | | |
  • Aren't you using any use directives in myTheme.theme? – kiamlaluno Jun 3 '17 at 6:04

The error is caused from the fact you didn't fully qualified the class name, which means you forgot the namespace of that class.

Or you use \Drupal\taxonomy\Entity\Term::load($tid); or you add a use \Drupal\taxonomy\Entity\Term; line at the top of the file. In this way, PHP knows where to find the class you reference.

| improve this answer | | | | |

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.