I have a view that in that view I set up 3 exposed filter, all working fine. I need to set a condition to show the third filter option to a specific user, it can be checked according to the user role, but how I should do that?

Can anyone provide a hook to help me?

Previously I tried the following but it does not change anything:

function my_modulename_form_alter(&$form, $form_state, $form_id) {

  if ($form_id == 'views_exposed_form') {




My view looks like this enter image description here


Following example unsets the filter average when user is NOT administrator, you can modify it to your specific case.

use Drupal\Core\Form\FormStateInterface;
function my_modulename_form_alter(&$form, FormStateInterface $form_state, $form_id){

  $roles = \Drupal::currentUser()->getRoles();
  $is_user_admin = in_array("administrator", $roles);
  $is_exposed = $form_id == 'views_exposed_form';
  $is_filter_set = isset($form['average']);

  if ( $is_exposed && $is_filter_set && !$is_user_admin ) {

If you want to unset only on a specific view exposed form use this condition

$is_our_view = $form["#id"] == "views-exposed-form-article-page-1";
  • unset($form['average']); not working for me and I use the $form['field_regions_target_id']['#access']=false; in my case, thanks. – Nasser May 1 at 5:55
  • 2
    I thought your filter id was average (from your question), try unset($form['field_regions_target_id']) – GiorgosK May 1 at 7:59

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.