I am working on porting a module from Drupal 7 to Drupal 8.
In the process I have to port a ctools content type plugin to the new context aware plugin.
The legacy plugin had "node" as a required context because it had to appear only on the node pages. I am finding it hard to implement it in the new plugin system.
Here is how I define the new plugin

 * Provides a 'Custom' block for the current node.
 * @Block(
 *   id = "machine_name_of_block",
 *   admin_label = @Translation("Admin label for the block"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node", required = FALSE)
 *   }
 * )
class ModuleBlock extends BlockBase {
   * {@inheritdoc}
  protected function blockAccess(AccountInterface $account) {
    /** @var $user \Drupal\user\UserInterface */
    // $user = $this->getContextValue('user');
    $node = $this->getContextValue("node");
    if (!is_null($node)) {
      return AccessResult::allowed();
    else {
      return AccessResult::forbidden();

   * {@inheritdoc}
  public function build() {
    // Sample output which will be changed later.
    return array('#markup' => '<span>' . $this->t('Powered by <a href="@poweredby">Drupal</a>', array('@poweredby' => 'https://www.drupal.org')) . '</span>');


I have a problem in accessing the context value in this plugin using $this->getContextValue('node');. It seems to return null even if I am on a node page.
Am I missing something?


Why don't you just use the existing node type condition plugin?

That won't solve your problem if you also need the node to actually display something, but core currently just doesn't really do this for blocks, there is no UI to configure the mapping, so it only works if the context has the exact same name.

You will likely have to fall back to getting the parameter yourself out of the route match service, for now.

  • I did not go for the node type condition plugin because I wanted to display some data about the current node from the current node. There are other ways to achieve this offcourse, but I am just wondering if the context work for the condition plugin, why was this not implemented for the block plugin. This was doable with ctools content type by passing the 'required context' in D7. Scope for a new core issue? ;-)
    – AjitS
    Jun 29 '15 at 12:29
  • 2
    No need for a new issue, there's drupal.org/node/2377757.
    – Berdir
    Jun 29 '15 at 12:30
  • was about to say: At first look, the contextDefinition isn't really taken into account on blockManager. So anything we add in definition won't have any effect. but @Berdir covered it all :)
    – vijaycs85
    Jun 29 '15 at 12:47

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.