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.

  • 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 at 17:19
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']);
  }
}
| improve this answer | |
  • Nothing is changed. Cleared the cache also. – Aniruddha Nath Apr 20 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 at 9:20
  • check my update – berramou Apr 20 at 9:20
  • Checked, but no effect. – Aniruddha Nath Apr 24 at 16:07
  • 1
    I've achieved this by using Better Exposed Filter module. – Aniruddha Nath Apr 28 at 9:33

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.