I'm trying to limit terms in a view facet (exposed filter) based on a contextual filter.
I have products with a 'category/type' taxonomy term. The terms are 2-level, looking roughly like this:
- Category 1
- Type a
- Type b
- Type c
- Category 2
- Type d
- Type e
- Type f
We can assign multiple terms from the 2nd level to each product.
I have a view that shows only products within a 1st level category (e.g. Category 1) by contextual filter, and then allow the user further filter by 'Type' from a facet (should show 'Type a', 'Type b', 'Type c' when contextual filter is 'Category 1').
The problem is that, since we can assign terms from multiple categories to the same product, we are seeing types from 'Category 2' in the facets, despite the fact that we're filtering by 'Category 1'.
Is there a hook to alter the facets, based on the contextual filter applied to the view?
So far, I got as far as eliminating an option from an exposed filter:
use \Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_form_views_exposed_form_alter().
*/
function cd_general_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$view_ids = [
'duplicate_of_product_category_by_material',
'product_category_by_material',
];
if ($form_id == 'views_exposed_form' && in_array($form_state->get('view')->id(), $view_ids)) {
unset($form['field_category_target_id']['#options'][118]);
}
}
To test, I duplicated my view so that I have one with normal exposed filters, and the original with facets related to those filters. The code above works on the exposed filters, but not on my facets.
My next step is to look again for hooks in the facets and core_views_facets modules.