To programatically change an exposed filter value in Drupal 9 based on another exposed filter, you can use the following steps:
Implement the hook_form_alter() function in a custom module. This function allows you to alter the form elements of a Drupal form.
In the hook_form_alter() function, find the two exposed filters in the form using their element IDs. You can use the dpm() or kint() functions from the Devel module to inspect the form elements and find their IDs.
Add an AJAX callback to the first exposed filter using the #ajax property. This callback will be triggered when the first filter's value is changed.
In the AJAX callback function, use the Drupal.ajax() function to send a request to the server and retrieve the filtered results. You can use the Drupal Views module's built-in AJAX callbacks to retrieve the filtered results.
Once you have retrieved the filtered results, use the Drupal.views.instances[] object to find the view's exposed form and update the value of the second exposed filter using jQuery.
Here is some example code to get you started:
use Drupal\Core\Form\FormStateInterface;
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'views_exposed_form' && $form['#id'] == 'MY_VIEW_ID') {
// Find the two exposed filters in the form.
$first_filter = &$form['MY_FIRST_FILTER'];
$second_filter = &$form['MY_SECOND_FILTER'];
// Add an AJAX callback to the first exposed filter.
$first_filter['#ajax'] = [
'callback' => 'MY_AJAX_CALLBACK',
'wrapper' => 'MY_VIEW_WRAPPER',
'event' => 'change',
];
}
}
function MY_AJAX_CALLBACK($form, FormStateInterface $form_state) {
// Retrieve the filtered results using Views AJAX callbacks.
$view = views_get_view('MY_VIEW_ID');
$view->setExposedInput($form_state->getValues());
$view->preExecute();
$view->execute();
$result = $view->render();
// Update the value of the second exposed filter using jQuery.
$settings = [
'MY_SECOND_FILTER' => $result['MY_SECOND_FILTER']['#options'],
];
$commands[] = [
'command' => 'MY_UPDATE_SECOND_FILTER',
'settings' => $settings,
];
return [
'#type' => 'ajax',
'#commands' => $commands,
];
}
In the above code, replace MY_VIEW_ID, MY_FIRST_FILTER, and MY_SECOND_FILTER with the appropriate IDs for your view and exposed filters. You will also need to define the MY_UPDATE_SECOND_FILTER JavaScript function to update the value of the second exposed filter using jQuery.
With this code, when the user changes the value of the first exposed filter, an AJAX request will be sent to the server to retrieve the filtered results. The value of the second exposed filter will then be updated based on the filtered results.