简体   繁体   English

hook_form_FORM_ID_alter:前 select 一个复选框,来自 drupal 8 视图中的暴露过滤器

[英]hook_form_FORM_ID_alter: Pre select a checkbox from an exposed filter in a drupal 8 view

I have a view that lists blog articles.我有一个列出博客文章的视图。 The blog content type has a taxonomy reference field to the 'tags' vocabulary, authors can select 1 or multiple tags.博客内容类型有一个“标签”词汇的分类参考字段,作者可以 select 1 个或多个标签。 The view exposes the 'Has taxonomy terms (with depth) (exposed)' filter (as a list of checkboxes) so that users can search for blog articles containing 1 or more tags.该视图公开了“具有分类术语(具有深度)(公开)”过滤器(作为复选框列表),以便用户可以搜索包含 1 个或多个标签的博客文章。

Now, i'm trying to pre-select 1 of the checkboxes that are exposed to the user in the hook_form_FORM_ID_alter() hook.现在,我正在尝试在 hook_form_FORM_ID_alter() 挂钩中预先选择向用户公开的 1 个复选框。 It should be a simple as the code below but it just doesn't work.它应该像下面的代码一样简单,但它不起作用。 The tag i'm trying to pre-select has the ID 288.我尝试预选的标签的 ID 为 288。

What am i doing wrong?我究竟做错了什么? Thx...谢谢...

    function xtheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{

    if($form['#id'] == 'views-exposed-form-vcon-finder-page-1'){
        $form['tags']['#default_value'] = [288 => 288];
    }

}

You have to set user input like this:您必须像这样设置user input

function xtheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    if($form['#id'] == 'views-exposed-form-vcon-finder-page-1'){
        if (is_null(\Drupal::request()->get('tags'))) {  
        // Avoid overriding the filter values selected by user
            $input = $form_state->getUserInput();
            $input['tags'] = [288 => 288];
            $form_state->setUserInput($input);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM