"Call to a member function label() on null", while it's defined I'm using a module_suggestions_alter hook to force (or not) which template must be used in a specific case. The custom template I chose must is used in several cases, but sometimes, the default template must be used instead.

A while ago, I discovered that having too much templates for one node causes Drupal to choose the wrong template. I also discovered that I can remove the other suggestions so that I'm sure Drupal will choose the right template.

Now, I'd like to do the following: if the node type is equal to "node type 1" or "node type 2" (for example), then I unset every suggestions so Drupal uses the default template, node.html.twig. If not, I leave my custom template as a suggestion


  Disclaimer : I don't know if my "method" is the best one, but this is all I could think about. Feel free to tell me if this is heresy.


Here is my code:

function module_pdf_theme_suggestions_alter(array &amp;$suggestions, array $variables, $hook) {

  $node_type = ['node type 1', 'node type 2'];
  $view_mode = "node__module_pdf";
  $type = $variables['elements']['#node']-&gt;type-&gt;entity-&gt;label();
  // Outputs 'node type 1' if I do a die(kpr($type));

  if(in_array($type, $node_type)) {
    $view_mode = '';
  }

  if($variables['elements']['#view_mode'] === 'module_pdf') {
    foreach($suggestions as $i =&gt; $suggestion) {
      if($suggestion !== $view_mode) {
        unset($suggestions[$i]);
      }
    }
  }
}


So, as I told you, if the node type is equal to one of the elements that I set in the array, it will "erase" the $view_mode content. This way, the foreach will unset everything, and tell Drupal to use node.html.twig.

My main problem however, is that even though $type gives me the correct node value when tested, it will cause a server error if I use it in my foreach, and I don't know why. Error output is the following:

Error: Call to a member function label() on null


I tried a verification to check if the node type existed, but nothing changed. How can I fix this?
You have to check if you are in a node hook: 

if ($hook != 'node') {
  return;
}


In other hooks you don't have a node object and the function label() is called on null.

Though you might want to check the machine name of the node type, because the display name can change when you have multiple languages:

$node-&gt;getType()