autocomplete - 如何过滤 Drupal8 中的自动完成值?
问题描述
有 2 个分类变量州和城市我需要将它们添加到内容类型。其中,一个是下拉列表(选择列表),另一个是自动完成列表。这里的自动完成列表取决于选择列表。
假设我们在州有术语(加利福尼亚州、亚利桑那州、俄亥俄州、北达科他州)和城市中的术语(桑尼维尔、帕洛阿尔托、克利夫兰、哥伦布、凤凰城、塞多纳、俾斯麦、詹姆斯敦)
当用户从选择列表中选择一个州时,即 OH,当他开始输入时,他会转到第二个下拉列表进行自动完成,它也应该只过滤自动完成列表中与 OH 相关的城市
解决方案
您可以通过在表单 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'];
}
推荐阅读
- php - 使用 PHP 运行 post 操作而不是从表单提交
- sql-server - 从 TFS 运行 SQL 代理作业
- web - 桌面应用程序开发所需的技能
- gis - 使用 Openlayers 3 单击鼠标并弹出 Overlay.is 不起作用
- jupyter-notebook - 从 papermill 生成的 notebook 可以用实时运行的内核输出吗?
- google-chrome - 从 Chrome 网上应用店下载 CRX 文件时出错:CRX_HEADER_INVALID
- tensorflow2.0 - 为什么`keras.experimental.SequenceFeature`的输入必须是`SpareTensor`?
- python - 文件中的%是什么意思
- android - 如何在 kotlin 中实现 Android 应用购买?
- java - Spring Boot Rest 中的 504 Gateway Time-out 问题需要大量记录(超过 80K)