You need to pull the node object out of the variables array.
$node = $variables['node'];
In certain preprocess functions this may not be available, so you can try the request service:
$node = \Drupal::request()->get('node');
The object must be of type Node
. Therefore:
$node->getType() == 'events'
As Berdir mentioned, you should check and ensure that $node
is a valid Node
object to see if it is an instance of NodeInterface
before operating on it. This will prevent fatal errors in the event that $variables['node']
is actually a node and not some ad-hoc variable created in code from which you can't call methods on:
Example 1 (using $variables
array):
if (isset($variables['node']) && $variables['node'] instanceof NodeInterface) {
$node = $variables['node'];
$title = $node->getTitle();
$type = $node->getType();
// more code...
}
Example 2 (using the request):
$node = \Drupal::request()->get('node');
if (isset($node) && $node instanceof NodeInterface) {
$title = $node->getTitle();
$type = $node->getType();
// more code...
}