Jun 06, 2019 in Drupal 8, Snippets

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
/**
 * 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();
}