I've done this recently in a project of mine using MYMODULE_form_views_exposed_form_alter
. The code assumes you've a view with the term ID on first position as contextual filter, e.g. domain.com/myview/123
<?php
function MYMODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$view = $form_state->getStorage('view');
$display_id = $view['view']->current_display;
if ($form_id == 'views_exposed_form' && $view['view']->id() == 'MY_VIEW' && $display_id == 'MY_VIEWDISPLAY') {
if (!empty($view['view']->args) && $view['view']->args[0]) {
//get the term ID from the contextual filter
$contextTermId = $view['view']->args[0];
$entriesToRemove = [];
$currentFilterValue = $form_state->getUserInput()['FIELD_FILTER_TAXONOMY'];
foreach ($form['FIELD_FILTER_TAXONOMY']['#options'] as $idx => $entry) {
if ($idx === 'All') {
//remove the old root '- Any -' option
$entriesToRemove[] = $idx;
}
//the next line is a bit shaky might need rework:
//sometimes filter entries are a stdClass,
//but I've also seen entries as array in other exposed forms (grouped filters?)
elseif ($entry instanceof stdClass && is_array($entry->option)) {
$termId = key($entry->option);
$termName = current($entry->option);
//the context filter term is our new root, so we change its label to '- Any -'
if ($termId == $contextTermId) {
$form['FIELD_FILTER_TAXONOMY']['#options'][$idx]->option = [$termId => t('- Any -')];
if (empty($currentFilterValue) || $currentFilterValue == 'All') {
//we've removed the default empty/All entry, reset it to our newly created, faked '- Any -' category
$form_state->setUserInput(['FIELD_FILTER_TAXONOMY' => $contextTermId]);
}
}
else {
//this is the core part: for each filter option load the term
//and check if it is a child of the contextual filter term
$parents = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadParents($termId);
if (!in_array($contextTermId, array_keys($parents))) {
$entriesToRemove[] = $idx;
}
else {
//optional: we are in a sub-filter now,so we no longer need the leading '-' to indicate hierarchy
$form['FIELD_FILTER_TAXONOMY']['#options'][$idx]->option = [$termId => trim(preg_replace('/^-/', '', $termName))];
}
}
}
}
foreach ($entriesToRemove as $idx) {
unset($form['FIELD_FILTER_TAXONOMY']['#options'][$idx]);
}
//optional: if there is only 1 entry left, hide the filter
if (count($form['FIELD_FILTER_TAXONOMY']['#options']) == 1) {
$form['FIELD_FILTER_TAXONOMY'] = [
'#type' => 'hidden',
'value' => $contextTermId
];
}
}
}
}
A word of caution: Don't to this on huge taxonomies, my code loads every taxonomy term to decide if it needs to be removed.