0

I have a view with exposed filters, in Drupal 8. I need to set the default value of a filter to its title or custom text. I also need to unset/remove the - Any - option from the select list.

How can I achieve this?

Here is my code:

    function bootstrap_barrio_subtheme_form_alter(&$form, FormStateInterface 
    $form_state, $form_id) {
        if ($form_state['view'] == 'office_locations_doctor_detail') {
            $form['field_doctor_reference_target_id_1']['#default_value'] = 
            'Select Doctor';
        }
     }

Cleared the cache and reload the page but nothing changed.

1
  • 3
    Welcome to Drupal Answers! đź‘‹ You can do that by implementing hook_form_alter in a custom module or theme. And then I think you simply have to set the '#default_value' of this element. Have you tried that already?
    – leymannx
    Apr 18, 2020 at 17:19

1 Answer 1

2

Try this:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function bootstrap_barrio_subtheme_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ( $form_state->get('view')->id() == 'office_locations_doctor_detail'){
     // Set the default value as tid not the name of term.
     // Change 'Select Doctor' by the tid of it.
    $form['field_doctor_reference_target_id_1']['#default_value'] = '1';
    // Remove - Any - option. 
    unset($form['field_doctor_reference_target_id_1']['#options']['All']);
  }
}
5
  • Nothing is changed. Cleared the cache also. Apr 20, 2020 at 5:02
  • if nothing changed, make sure that your theme name is bootstrap_barrio_subtheme and change the view name from àrticles` to your view name office_locations_doctor_detail for example, and make sure also the your field machine name is field_doctor_reference_target_id_1
    – berramou
    Apr 20, 2020 at 9:20
  • check my update
    – berramou
    Apr 20, 2020 at 9:20
  • Checked, but no effect. Apr 24, 2020 at 16:07
  • 1
    I've achieved this by using Better Exposed Filter module. Apr 28, 2020 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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