I select "Configuration type" as a Block and select my custom block to export the configuration from development/configuration/single/export, I got following configurations in Visibility of block.

If I want to set visibility programmatically, how can I do this?

    id: _menu_position
      'main:menu_link_content:016650bb-ecd4-43e4-9d04-fef05ebcf186': 'main:menu_link_content:016650bb-ecd4-43e4-9d04-fef05ebcf186'
      'main:menu_link_content:2d195963-d98d-4f02-8129-6498c5db4b87': 'main:menu_link_content:2d195963-d98d-4f02-8129-6498c5db4b87'

For this, I have used following function,

function placeBlock(EntityInterface $entity) {

    $config = \Drupal::configFactory();
    $settings = [
        'plugin' => '_block_module_block', // Set the plugin id
        'region' => 'header', // Set region to header
        'id' => $entity->id() . '-_bm_autoheader', // Use the page id and the module name for machine name
        'theme' => $config->get('system.theme')->get('default'),
        'label' => $entity->label(), // Use the page label
        'visibility' => [],
        'weight' => 0,
        'label_display' => 0, // disable label
        'page_id' => $entity->id(), // Reference page
    $values = [];
    foreach (['region', 'id', 'theme', 'plugin', 'weight', 'visibility'] as $key) {
        $values[$key] = $settings[$key];
        // Remove extra values that do not belong in the settings array.

    foreach ($values['visibility'] as $id => $visibility) {
         $values['visibility'][$id]['id'] = $id;

    $values['settings'] = $settings;
    $block = Block::create($values);

In my case, $visibility array getting null.

langcode: de
status: true
    - _block_module
    - _drupal_theme
id: 57148-_bm_autoheader
theme: _drupal_theme
region: header
weight: 0
provider: null
plugin: _block_module_block
  id: _block_module_block
  label: 'Header Contact'
  provider: _block_module
  label_display: '0'
  page_id: '57148'
visibility: {  }

'visibility' => [],

Need help to understand the Visibility portion of the block. How it works in D8 and how we can set programmatically?

Thanks in advance.


I have found the solution, set the visibility configuration by the following function using $menuLinkItem->uuid().

function setVisibilityConfig($instance_id, array $configuration)

$block->setVisibilityConfig('_menu_position', array('id' => '_menu_position',
        '_menu_position'=> [
              'main:menu_link_content:'.$menuLinkItem->uuid() => 'main:menu_link_content:'.$menuLinkItem->uuid()
        'negate' => null,

Thanks, @SumitMadan for helping out to understand the visibility concept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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