Control block access programmatically in drupal 8

Block access is a powerful way to show or hide content in some contexts. Instead of using contrib modules, this is very easy in small pieces of custom code. The following code prevents access to a block based on a subscription field in the user object.

// snippet: https://stefvanlooveren.me/node/75
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

/**
 * Implements hook_block_access().
 */
function MYMODULE_block_access(Block $block, $operation, AccountInterface $account) {
  $blockAccess = TRUE;
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $subscription = $user->get('field_subscription')->value;
  if($subscription == 'expired') {
    $blockAccess = FALSE;
  }
  if ($operation == 'view' && $block->getPluginId() == 'MY_BLOCK_ID') {
    return AccessResult::forbiddenIf($blockAccess == FALSE)->addCacheableDependency($block);
  }
  return AccessResult::neutral();
}

 

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!