I have a view that lists blog articles. The blog content type has a taxonomy reference field to the 'tags' vocabulary, authors can select 1 or multiple tags. The view exposes the 'Has taxonomy terms (with depth) (exposed)' filter (as a list of checkboxes) so that users can search for blog articles containing 1 or more tags.
Now, i'm trying to pre-select 1 of the checkboxes that are exposed to the user in the hook_form_FORM_ID_alter() hook. It should be a simple as the code below but it just doesn't work. The tag i'm trying to pre-select has the ID 288.
What am i doing wrong? Thx...
function xtheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
if($form['#id'] == 'views-exposed-form-vcon-finder-page-1'){
$form['tags']['#default_value'] = [288 => 288];
}
}
You have to set user input
like this:
function xtheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if($form['#id'] == 'views-exposed-form-vcon-finder-page-1'){
if (is_null(\Drupal::request()->get('tags'))) {
// Avoid overriding the filter values selected by user
$input = $form_state->getUserInput();
$input['tags'] = [288 => 288];
$form_state->setUserInput($input);
}
}
}