首页 > 解决方案 > 如何过滤 Drupal8 中的自动完成值?

问题描述

有 2 个分类变量州和城市我需要将它们添加到内容类型。其中,一个是下拉列表(选择列表),另一个是自动完成列表。这里的自动完成列表取决于选择列表。

假设我们在州有术语(加利福尼亚州、亚利桑那州、俄亥俄州、北达科他州)和城市中的术语(桑尼维尔、帕洛阿尔托、克利夫兰、哥伦布、凤凰城、塞多纳、俾斯麦、詹姆斯敦)

当用户从选择列表中选择一个州时,即 OH,当他开始输入时,他会转到第二个下拉列表进行自动完成,它也应该只过滤自动完成列表中与 OH 相关的城市

标签: autocompletedrupal-8

解决方案


您可以通过在表单 alter 中使用 #ajax 来实现此目的。此外,您需要创建一个具有父子关系的分类,而不是两个单独的分类。

使用 Contribute 模块简单的分层选择

或者

以下是自定义示例代码:

function example_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  switch ($form_id) {
    case 'example_form':

      $states = [];
      $vid    = 'states';
      $terms  = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, 0, NULL, FALSE);
      foreach ($terms as $term) {
        if ($term->depth == 0)
          $states[$term->tid] = $term->name;
      }

      $form['states'] = [
        '#title'      => t('States'),
        '#type'       => 'select',  
        '#options'    => $states,        
        '#required'   => TRUE,
        '#ajax' => [
          'callback'  => 'getCityList',
          'event'     => 'change',
          'wrapper'   => ['autocomplete_city_container'],
          'method'    => 'replace',
          'effect'    => 'slide',
          'progress'  => [
            'type'    => 'throbber',
            'message' => t('Fetching city...'),
          ],
        ]      
      ];

      $form['city_alter'] = [
        '#type'       => 'container',
        '#attributes' => ['id' => ['autocomplete_city_container']],     
      ];
      $form['city_alter']['city'] = array(
          '#title'    => t('City'),
          '#type'     => 'select',   
          '#required' => TRUE,
          '#options'  => [],                
        );
      if (!empty($form_state->getValue('states'))) {
        $cities   = [];
        $stateTid = $form_state->getValue('states');
        $vid      = 'city';
        $terms    = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, $stateTid, NULL, FALSE);
        foreach ($terms as $term) {                
            $cities[$term->tid] = $term->name;
        }

        $form['city_alter']['city'] = array(
          '#title'    => t('Size'),
          '#type'     => 'select', 
          '#required' => TRUE,
          '#options'  => $cities,                
        );
      }
    break;
  }
}
function getCityList(array &$form, FormStateInterface $form_state) {  
  return $form['city_alter'];
}

推荐阅读