Drupal, Views Exposed Filters: List Options Containing Results
I'm setting up an apartment search site and have exposed a views filte开发者_C百科r for 'property type'. The property type is a select field with 16 options but the client only wants those options that actually contain results to appear in the drop down of the exposed filter.
Any ideas?
Thanks!
You could use form_alter, Take a look at: http://drupal.org/node/463990, or http://drupal.org/project/better_exposed_filters for usage specific to exposed filters.
this is what you want http://drupal.org/project/views_hacks#views_filters_selective
Views Selective Exposed Filters On list and checkbox exposed filters, you can specify the filter option "Limit list to result set" to only display values that are actually returned in the view's results. The filter option "Further limit list to active filters" restricts the displayed values to view results obtained by applying exposed filter values.
In Drupal 8, I was able to display only tags with results with the following code. Note that I'm using Better Exposed Filters contrib module, and display my filter as a Select.
function mymodule_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form['#id'] == 'views-exposed-form-your-view-name-page') {
if (array_key_exists('field_activities_target_id', $form)) {
// Rewrite the default 'All' option
if (!empty($form['field_activities_target_id']['#options']['All'])) {
$option_default = ['All' => t('Choose a category')];
}
$options = $form['field_activities_target_id']['#options'];
$connection = Database::getConnection();
$query = $connection->select('node__field_activities', 'activities');
$query->join('node_field_data', 'n', 'n.nid = activities.entity_id');
$query->fields('activities', ['field_activities_target_id']);
$query->fields('n', ['status']);
$query->condition('activities.bundle', 'your_node_type_name');
$query->condition('n.status', 1);
$data = $query->distinct()->execute();
$results = array_flip($data->fetchAll(\PDO::FETCH_COLUMN, 'field_activities_target_id'));
$options = array_intersect_key($options, $results);
// Rebuild the option select
$form['field_activities_target_id']['#options'] = $option_default + $options;
}
}
}
This article was a great help : https://johndevman.com/only-show-options-in-a-views-exposed-filter-that-belong-to-result-set/
For Drupal 8 I have found this module very helpful: https://www.drupal.org/project/selective_better_exposed_filters
This works for taxonomy term
based fields.
精彩评论