TestContextAwareBlock.php

Same filename and directory in other branches
  1. 9 core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php
  2. 8.9.x core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php
  3. 11.x core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php

Namespace

Drupal\block_test\Plugin\Block

File

core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php

View source
<?php

namespace Drupal\block_test\Plugin\Block;

use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\user\UserInterface;

/**
 * Provides a context-aware block.
 */
class TestContextAwareBlock extends BlockBase {
  
  /**
   * {@inheritdoc}
   */
  public function build() {
    /** @var \Drupal\user\UserInterface $user */
    $user = $this->getContextValue('user');
    return [
      '#prefix' => '<div id="' . $this->getPluginId() . '--username">',
      '#suffix' => '</div>',
      '#markup' => $user ? $user->getAccountName() : 'No context mapping selected.',
    ];
  }
  
  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    if ($this->getContextValue('user') instanceof UserInterface) {
      $this->messenger()
        ->addStatus('User context found.');
    }
    return parent::blockAccess($account);
  }

}

Classes

Title Deprecated Summary
TestContextAwareBlock Provides a context-aware block.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.