0

Found it useful and did not find any contributed module to fulfil this so, adding it for knowledge purpose.

Stuck in a situation where we need to hide a block for certain role.

Drupal 8 has functionality to hide for certain URLS.

But, for Roles, only show condition is there not Hide.

I have already answered my question and I would love to accept another solutions.

Please suggest a solution.

1
  • Added the question and answer here so that other people might be facing the same issue I was facing. Thanks for closing this question.
    – Pupil
    Commented Mar 18, 2021 at 3:56

1 Answer 1

2

There are visibility settings where, we can select which pages the block can be visible.

The same form has an underlying functionality to hide the block for the selected list or URLs.

Unfortunately, the same is not the case of Roles.

You can select which roles you want to display the block, but, you cannot select which Roles you want to hide the block.

Following code adds a Negate condition to Roles Visibility:

/* Negate the condition to decide visibility of which user roles to show/hide. */
function YOUR_MODULE_form_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['visibility']['user_role']['negate'] = [
        '#type' => 'radios',
        '#title' => '',
        '#default_value' => 0,
        '#options' => [
            t('Show for selected Roles'),
            t('Hide for selected Roles'),
        ],
    ];
}

This adds two radio buttons under the form: Roles.

Following is the screen shot for the same:

enter image description here

Reference:

2
  • 1
    I wouldn't overwrite the default value, it is already present and you need it when you edit the block. This is because the roles condition plugin is correctly implementing the negate condition, but then it is replaced by an invisible value form element in the block form. The reason why is unclear. See this issue drupal.org/project/drupal/issues/2986958, also for a patch.
    – 4uk4
    Commented Mar 17, 2021 at 13:31
  • 1
    Nice little module. I'd create a variable $default_value and then if $form['visibility']['user_role']['negate']['#default_value'] is set, use it instead of zero. Commented Aug 18, 2022 at 20:15

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