[英]How to change the label of the default value (-Any-) of an exposed filter in Drupal Views?
[英]How can I dynamically change the default value for views exposed filter referencing taxonomy terms when the term weight value = 0
我在一个视图中有一个暴露的过滤器正在引用特定词汇表中的分类术语。 运算符(下面的屏幕截图)允许选择一个术语作为该过滤器的默认值。 我想要实现的是动态 select 项权重 = 0 时的默认值。
这应该允许权限较低的角色(如内容贡献者)通过更改术语的顺序(权重)来设置公开过滤器的默认值,而无需编辑视图设置。
我试图对此进行研究,到目前为止,实现这一目标的最佳方法似乎是使用 (hook_views_pre_build) 但我只是不知道如何。
经过广泛的搜索和实验,这段代码对我有用:
use Drupal\taxonomy\Entity\Term;
use Drupal\views\ViewExecutable;
/**
* Implements hook_views_pre_build().
*/
function YOUR_MODULE_NAME_views_pre_build(ViewExecutable $view) {
if ($view->id() == 'YOUR_VIEW_ID' && $view->current_display == 'YOUR_DISPLAY_ID') {
// Get the exposed filter for the taxonomy terms.
$filter = $view->display_handler->getHandler('filter', 'YOUR_FILTER_ID');
if ($filter) {
// Query the database for taxonomy terms with a weight of 0.
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('weight', 0);
$term_ids = $query->execute();
if (!empty($term_ids)) {
// Load the first term found with a weight of 0.
$term = Term::load(array_shift($term_ids));
if ($term) {
// Set the default value for the exposed filter to the term's ID.
$filter->options['value'] = $term->id();
}
}
}
}
}
当预先构建指定视图时,此代码将在数据库中查询权重为 0 的分类术语,并将公开过滤器的默认值设置为其找到的第一个术语的 ID。 如果没有找到权重为 0 的项,则不会更改默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.