3 namespace Drupal\block_test\Plugin\Block;
5 use Drupal\Core\Block\BlockBase;
6 use Drupal\Core\Session\AccountInterface;
7 use Drupal\user\UserInterface;
10 * Provides a context-aware block.
13 * id = "test_context_aware",
14 * admin_label = @Translation("Test context-aware block"),
16 * "user" = @ContextDefinition("entity:user", required = FALSE)
20 class TestContextAwareBlock extends BlockBase {
25 public function build() {
26 /** @var $user \Drupal\user\UserInterface */
27 $user = $this->getContextValue('user');
29 '#prefix' => '<div id="' . $this->getPluginId() . '--username">',
30 '#suffix' => '</div>',
31 '#markup' => $user ? $user->getUsername() : 'No context mapping selected.' ,
38 protected function blockAccess(AccountInterface $account) {
39 if ($this->getContextValue('user') instanceof UserInterface) {
40 $this->messenger()->addStatus('User context found.');
43 return parent::blockAccess($account);