您可以通过在表单 alter 中使用 #ajax 来实现此目的。
此外,您需要创建一个具有父子关系的分类,而不是两个单独的分类。
使用贡献模块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'];
}