We have a view for the Basic page content type, which has a Category field that allows to enter multiple values.
All values for Category are displayed (IoT, Cloud, Security), but there are only nodes that use IoT and Cloud. I want to display only IoT and Cloud for the Category exposed filter.
How can I limit the exposed filters to only display values for which content exists?
The view settings are the following.
Format- Show: Content | Teaser
- Format: Unformatted List | Settings
- Authored on (exposed)
- Category (field_category) (exposed) | Settings (settings is set to Category tag, selection type = Dropdown)
- Author (exposed)
- Published (= Yes)
- Content Type (= Basic Page)
- Content: Authored on (desc)
- None
- Exposed form style: Better Exposed Filters | Settings
- Settings are set to default in Better Exposed Filters
- Use Ajax: Yes
- Use aggregation: no
- query settings: default settings
Here is what we tried. This only gets me the nodes that have a value for field_category
and all term values for categories
term individually.
function mymodule_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$node_storage = Drupal::getContainer()->get('entity_type.manager')->getStorage('node');
$node_ids = $node_storage->getQuery();
// This returns all nodes with a value for *field_category*.
$nodes = $node_ids->condition('type','page')
->exists('field_category')
->condition('status', 1)
->sort('title')
->execute();
// returns all taxonomy terms.
$category_tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('categories');
}