1

I am trying to make a block that gets the current node via Plugin Contexts.

But my $node is always null. Can anyone tell me why?

I am placing the block with the context module if that makes a difference?

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Header' block.
 *
 * @Block(
 *   id = "header",
 *   admin_label = @Translation("Header"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node", required = FALSE)
 *   }
 * )
 */
class ProductStickyHeader extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $node = $this->getContextValue('node');
    // $node is always null!

    return $build;
  }
}

Many thanks!

1
  • 1
    "I am placing the block with the context module if that makes a difference?" Yes that possibly makes all the difference, quite possible that the context module doesn't support that. Try using the default block UI to confirm that
    – Berdir
    Commented Sep 19, 2017 at 11:11

2 Answers 2

2

Thanks everyone - turns out the answer was deceptively simple - I had to remove the block using context & then re-add it. When I re-added it there was an extra option in context to use the current node. Then the context plugin worked!

0

The most common way to get the current node in a block is to use the route parameters. E.g.:

$node = \Drupal::routeMatch()->getParameter('node');
if ( $node == NULL || $node->getType() != 'blog_post') {
  return;
}
1
  • The recommended way is definitely to use block contexts not this, because that will for example take care of cache contexts, which this does not and you need to make sure your block is properly cached yourself. But if the module instantiating the block plugins doesn't support that, then you need to fall back to this, yes
    – Berdir
    Commented Sep 19, 2017 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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