2

I have a view that in that view I set up 3 exposed filter, all filtering working fine.

  • First: Filter by contact first name
  • Second: Filter by Project name
  • Third: Filter by Contact region/location

The third filter should be shown just for specific logged in user, and that user should be Administrator.

I tried the following codes and it does not working, even doesn't show the Var_dump, so how should it change to work?

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

  if ($form_id == 'views_exposed_form') {

    //unset($form['average']);

    var_dump($form);

    die();
  }
}

Here I attached my view configuration and settings may help you to get what I have in my view

enter image description here

1
  • May you provide the exact code you are using? Showing a if statement and saying it does not change anything is quite broad. I doubt that is the real code you are using; if that is the code you wrote so far, then the question is really broad.
    – apaderno
    Sep 2, 2019 at 11:41

1 Answer 1

5

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 ) {
    unset($form['average']);
  }
}

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";
2
  • unset($form['average']); not working for me and I use the $form['field_regions_target_id']['#access']=false; in my case, thanks. May 1, 2019 at 5:55
  • 3
    I thought your filter id was average (from your question), try unset($form['field_regions_target_id'])
    – GiorgosK
    May 1, 2019 at 7:59

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