This is this drop-down list for the field field_gender on the view whose name is members:

  • M|Male
  • F|Female

I know the following callback is executed (tested with var_dump...), but it doesn't do what I think it should do: Provide only the option which value is "M" for "Male" (this choice is decided programmatically, Views UI won't work).

Here is the callback:

/**
* Implementation of hook_views_pre_...().
*/
// function mymodule_views_pre_render(&$view){
// function mymodule_views_pre_build(&$view){
function mymodule_views_pre_execute(&$view){
    if ($view->name == 'members') {

        // get our filters
        $filters = $view->display_handler->get_option('filters');

        // Force
        $filters['field_gender_value']['value'] = array('M' => 'M');

        // apply changes
        $view->display_handler->override_option('filters', $filters);
    }    
}
up vote 2 down vote accepted

You use hook_form_alter:

/**
 * Implementation of hook_form_alter().
 */
  function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
  case 'views_exposed_form':
    // Force
    $form['field_gender_value']['#options'] = array('M' => 'M');
    break;
  }
}   
  • 1
    It is amazing how this answer was down-voted, when the OP then answered saying they used this hook. – kiamlaluno May 28 '16 at 12:06
  • This Hook works in Drupal 8 too. Thank you very much. – Achraf JEDAY Apr 21 at 12:28

If it is a select field, the time you will be adding it as expose filter you will get option to narrow down your options. Check the screenshot

enter image description here

  • Actually this won't work for, I need to do it programmatically (depending on using gender) – Nabil Kadimi Oct 4 '13 at 6:46

Although I prefer using Views API I went with hook_form_alter. This is how I did it.

/**
 * Implementation of hook_form_alter()
 */
function mymodule_form_alter(&$form,$form_state,$form_id) {

    switch ($form_id) {
        /*
            ...
        */
        case 'views_exposed_form':
            if($form['#id'] === 'views-exposed-form-members-page'){

                // Get the user gender
                global $user;
                $user = user_load($user->uid);
                $user_gender = $user->field_gender[LANGUAGE_NONE][0]['value']; 

                // Get available exposed options
                $exposed_options = $form['field_gender_value']['#options'];

                // Override options by whitelisting only the user gender 
                $form['field_gender_value']['#options'] = array_intersect_key($exposed_options, array_flip(array ($user_gender)));

            }
    }
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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