Hello I have created a module to display a block. I would like to set the block visibity to visible and hidden in the homepage based on a condition.

like this:


//fetch status from database then check condition
if ($status = 1){
//make block visible
//hide block

I have searched all over the internet and could not find how to make it work.

I have a form that is used to add contents to a database and it has a checkbox to whether make the make the block visible or not.

So I would fetch the status(visible/hidden) of the block from the database and then make the block visible.

  • Why not create a new visibility context instead of this?
    – Kevin
    Nov 24, 2021 at 11:12
  • hello @Kevin thanks for your comment. Can you please give me more information about this, actually I am new to drupal.
    – ImMrBlack
    Nov 24, 2021 at 11:19
  • We need more information about the condition in order to give you the best solution as in Drupal, you can do this multiple ways: in the block configuration, hooks and/or twig templates
    – NicklasF
    Nov 24, 2021 at 11:37
  • @NicklasMandrupFrederiksen I have just updated the question do check it please
    – ImMrBlack
    Nov 24, 2021 at 12:29
  • jaypan.com/tutorial/…
    – Kevin
    Nov 24, 2021 at 12:30

1 Answer 1


When you create a module to display a block this usually means you implement a block plugin. Then you can add the condition to the plugin directly:

  protected function blockAccess(AccountInterface $account) {
    $access = $this->languageManager->isMultilingual() ? AccessResult::allowed() : AccessResult::forbidden();
    return $access->addCacheTags(['config:configurable_language_list']);

Example from core LanguageBlock::blockAccess().

  • Thanks this worked
    – ImMrBlack
    Nov 24, 2021 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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