有两个分类变量State和Cities,我需要将它们添加到内容类型中。其中,一个是下拉列表(Select List),另一个是Autocomplete列表。在这里,自动完成列表取决于选择列表。
比方说,州中的术语为(CA,AZ,OH,ND),城市中的术语为( Sunnyvale,Paloalto,Cleaveland,Columbus,Phoenix,Sedona,Bismark,Jamestown)
当用户从选择列表中选择一个州(即,OH ),并且当他开始键入时,他转到第二个下拉列表进行自动完成时,它也应该在自动完成列表中只过滤到OH的附属城市
发布于 2019-01-09 18:38:42
您可以通过在form alter中使用#ajax来实现此目的。此外,您需要创建一个具有父子关系的分类法,而不是两个单独的分类法。
使用Contribute模块Simple hierarchical select
或
以下是自定义示例代码:
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'];
}https://stackoverflow.com/questions/53948828
复制相似问题