Objective:
We need to change the select field to a list of checkboxes for one of our clients.
We decided to add this to our more_fields module so that the solution could be available for other projects.
Design:
We decided to base our logic on the “taxonomy_index_tid” filter (provided by the taxonomy module). For our filter, we will add a widget that allows you to select the field type (select, radio buttons, checkboxes).
Automatic creation of the views filter:
Filters are automatically created when the Drupal cache is rebuilt. Two hooks allow this action to be performed ( hook_views_data_alter et hook_field_views_data_alter ). hook_field_views_data_alter is more suitable in our case because we want to add this to each field that references a taxonomy term.
/**
*
* @file
* Provides views data for more_fields.module.
*/
use Drupal\field\FieldStorageConfigInterface;
/**
* Implements hook_field_views_data_alter().
*
* Views integration for entity reference fields which reference taxonomy terms.
* Adds a term relationship to the default field data.
*
* @see views_field_default_views_data()
*/
function more_fields_field_views_data_alter(array &$data, FieldStorageConfigInterface $field_storage) {
if ($field_storage->getType() == 'entity_reference' && $field_storage->getSetting('target_type') == 'taxonomy_term') {
foreach ($data as $table_name => $table_data) {
foreach ($table_data as $field_name => $field_data) {
if (isset($field_data['filter']) && $field_name != 'delta') {
// Add filter CheckboxList.
$data[$table_name]['more_fields_' . $field_name] = [
'title' => t('Custom filter term taxonomy'),
'group' => t('More fields'),
'filter' => [
'id' => 'more_fields_checkbox_list',
'title' => 'More fields : ' . $field_storage->getLabel(),
'field' => $field_name,
'help' => t('Offers multiple select display format, radios, checkboxes.')
]
];
}
}
}
}
}
Result in terms of extras configuration:
Note:
If you want to replace the default filter, use this approach and make sure that your hook is the last one to be executed. (Currently, hooks are executed in alphabetical order).
$data[$table_name][$field_name]['filter']['id'] = 'my_custom_module_plugin_filter_id';