How do i change the visibility of an existing block programmatically?

I created the block using yml, here's the configuration:

uuid: 67105709-2648-445e-9ddd-8b830a854d8d
langcode: en
status: true
    - pixelpin_openid_connect
    - system
    - bartik
id: openidconnectlogin
theme: bartik
region: content
weight: 0
provider: null
plugin: pixelpin_openid_connect_login
  id: pixelpin_openid_connect_login
  label: 'PixelPin OpenID Connect Login'
  provider: pixelpin_openid_connect
  label_display: visible
    id: request_path
    pages: /user/login
    negate: false
    context_mapping: {  }

The block visibility will change depending on whether a checkbox is checked so i cannot modify the existing block using yml (if that's even possible) unless you can call it in code.


You can load the block and modify the visibility settings:

$block = \Drupal\block\Entity\Block::load('openidconnectlogin');
$visibility = $block->getVisibility();
if (isset($visibility['request_path']['pages'])) {
  $visibility['request_path']['pages'] = '/new/path';
  $block->setVisibilityConfig('request_path', $visibility['request_path']);
| improve this answer | |
  • Hi @4k4, any idea how I can delete the visibility condition completely? – Tim Jul 23 '18 at 14:45

You can use the hook_block_view_alter or hook_block_access.

function your_module_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account) {
  // Update your condition according to your requirement.
  if ($operation == 'view' && $block->getPluginId() == 'system_powered_by_block' && $xyz_config == 'xyz') {
    return AccessResult::forbidden()->addCacheableDependency($xyz_config);

  return AccessResult::neutral()->addCacheableDependency($xyz_config);

You implement addCacheableDependency method to avoid caching. Suppose you want to forbid the access if $xyz_config is set to "xyz" value. After some time $xyz_config variable is changed so access should be allowed in that case. But it won't happen until you add addCacheableDependency method and pass the variable.

You can read more about Cache API in D8: https://www.drupal.org/docs/8/api/cache-api/cache-api

| improve this answer | |
  • Can you give an example? – Callum Jan 19 '17 at 11:42
  • @Callum Updated my answer with example code. – Sumit Madan Jan 20 '17 at 4:48
  • @SumitMadan - Can you please explain what is $xyz_config, I need to understand and wanted to block is non-cacheable. I created a block using function placeBlock(EntityInterface $entity) () and placed into header region, now I want to change visibility for each block. How can I do this? – latikas Jan 8 '18 at 8:13
  • @latikas I have updated my answer. Please check. – Sumit Madan Jan 8 '18 at 11:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.