class TestContextAwareBlock

Same name and namespace in other branches
  1. 11.x core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php \Drupal\block_test\Plugin\Block\TestContextAwareBlock
  2. 10 core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php \Drupal\block_test\Plugin\Block\TestContextAwareBlock
  3. 8.9.x core/modules/block/tests/modules/block_test/src/Plugin/Block/TestContextAwareBlock.php \Drupal\block_test\Plugin\Block\TestContextAwareBlock

Provides a context-aware block.

Plugin annotation


@Block(
  id = "test_context_aware",
  admin_label = @Translation("Test context-aware block"),
  context_definitions = {
    "user" = @ContextDefinition("entity:user", required = FALSE,
      label = @Translation("User Context"), constraints = { "NotNull" = {} }
    ),
  }
)

Hierarchy

Expanded class hierarchy of TestContextAwareBlock

File

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

Namespace

Drupal\block_test\Plugin\Block
View source
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);
  }

}

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