Score:0

Hide and unhide custom block programatically drupal 9

cn flag

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.

Kevin avatar
in flag
Why not create a new visibility context instead of this?
cn flag
hello @Kevin thanks for your comment. Can you please give me more information about this, actually I am new to drupal.
NicklasF avatar
us flag
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
cn flag
@NicklasMandrupFrederiksen I have just updated the question do check it please
Kevin avatar
in flag
https://www.jaypan.com/tutorial/custom-drupal-block-visibility-plugins-and-condition-plugin-api
Score:3
cn flag

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

cn flag
Thanks this worked
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.