0

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:

edit:


//fetch status from database then check condition
if ($status = 1){
//make block visible
}else{
//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.

New contributor
ImMrBlack is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
5
  • Why not create a new visibility context instead of this?
    – Kevin
    Nov 24 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 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 Nov 24 at 11:37
  • @NicklasMandrupFrederiksen I have just updated the question do check it please
    – ImMrBlack
    Nov 24 at 12:29
  • jaypan.com/tutorial/…
    – Kevin
    Nov 24 at 12:30
2

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().

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

Your Answer

ImMrBlack is a new contributor. Be nice, and check out our Code of Conduct.

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.