2

I need to programatically set the visibility of a block. I've loaded the block, and I know I need to use the Block::setVisibilityConfig method, but I don't know what the $instance_id variable is.

Does anyone know what to pass here to the function?

2
  • It's documented. You pass an instance of a visibility condition object (which implements ConditionInterface)
    – Clive
    Sep 1, 2016 at 11:33
  • Hi @Clive, thanks for your reply, but I don't understand it. I have the following code: use Drupal\block\Entity\Block; $block = Block::load('sitebranding'); $block->setRegion('content'); $block->save(); What can I add to call that function?
    – jmzea
    Sep 1, 2016 at 14:40

1 Answer 1

4

I got it. Example:

use Drupal\block\Entity\Block;

function mytheme_preprocess_html(&$variables)
{
    $block = Block::load('sitebranding');
    $block->setRegion('content');

    $visibility = $block->getVisibility();

    if (isset($visibility['request_path']['pages']))
    {
       unset($visibility['request_path']['pages']);
       $visibility['request_path']['negate'] = 0; 
       // $visibility['request_path']['pages'] = '/node/2';
       $visibility['request_path']['pages'] = \Drupal::config('mymodule.settings')->get('services_block_path_visibility');
       $block->setVisibilityConfig('request_path', $visibility['request_path']);
       $block->save();
    }
}

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.