[英]How can I dynamically change the default value for views exposed filter referencing taxonomy terms when the term weight value = 0
I have an exposed filter in a view is referencing taxonomy terms from specific vocabulary.我在一个视图中有一个暴露的过滤器正在引用特定词汇表中的分类术语。 The operator ( screenshot below ) allows selecting a term as the default value for that filter.运算符(下面的屏幕截图)允许选择一个术语作为该过滤器的默认值。 What I want to achieve is to dynamically select the default value when the term weight = 0.我想要实现的是动态 select 项权重 = 0 时的默认值。
This should allow less privileged roles like Content Contributors to set the default value for the exposed filter by changing the order (weight) of the term without the need to edit the views settings.这应该允许权限较低的角色(如内容贡献者)通过更改术语的顺序(权重)来设置公开过滤器的默认值,而无需编辑视图设置。
I tried to research this and so far, it seems the best way to achieve this is by using (hook_views_pre_build) but I just don't know how.我试图对此进行研究,到目前为止,实现这一目标的最佳方法似乎是使用 (hook_views_pre_build) 但我只是不知道如何。
After extensive search and experiment, this code worked for me:经过广泛的搜索和实验,这段代码对我有用:
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();
}
}
}
}
}
This code will query the database for taxonomy terms with a weight of 0 when the specified view is pre-built and set the default value for the exposed filter to the ID of the first term it finds.当预先构建指定视图时,此代码将在数据库中查询权重为 0 的分类术语,并将公开过滤器的默认值设置为其找到的第一个术语的 ID。 If no terms are found with a weight of 0, it will not change the default value.如果没有找到权重为 0 的项,则不会更改默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.