None of the other answers is fully correct, each one will only work in some cases. Before calling an object method, you have to check
- if the object exists,
- if the object is of the right type
- and if the object has that specific method/field.
The following code might look like a bit of an overkill, but it is the most bulletproof solution I've found so far. Everything I'm checking in there is based on a real word error I've had in my own projects:
function MYMODULE_preprocess_MYHOOK(&$variables) {
$route = \Drupal::routeMatch();
//special case node preview: has no node object, but a node_preview
if ($route->getRouteName() == 'entity.node.preview') {
$node = $route->getParameter('node_preview');
}
// this is the default case
else {
$node = $route->getParameter('node');
}
//$node can be either a node object (most of the times)
//or an integer (on some admin routes)
if (is_numeric($node)) {
$node = \Drupal\node\Entity\Node::load($node);
}
// this if-statement is the important part that prevents the error messages
if ($node instanceof \Drupal\node\NodeInterface && $node->hasField('field_MYFIELD')) {
// no you can savely do whatever you want with field_MYFIELD
$myVar = $node->get('field_MYFIELD')->value;
$isEmpty = $node->get('field_MYFIELD')->isEmpty();
}
}