You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Drupal 8配置表单中创建允许多值的实体引用字段?

如何在Drupal 8的表单中让entity_autocomplete字段支持多值输入?

嘿,要让你的page_title这个entity_autocomplete字段支持用户输入多个值其实很简单,只需要给字段配置加上几个关键属性就行,我给你修改好的完整代码,再给你解释下关键改动:

public function buildForm(array $form, FormStateInterface $form_state) { 
  $form = parent::buildForm($form, $form_state); 
  $config = $this->config('category_dynamic_block.settings'); 

  $form['section_title'] = array( 
    '#type' => 'textfield', 
    '#title' => $this->t('Section Title'), 
    '#description' => $this->t('Enter a Section Title'), 
    '#default_value' => $config->get('section_title'),
  ); 

  $form['term_name'] = array( 
    '#type' => 'entity_autocomplete', 
    '#target_type' => 'taxonomy_term', 
    '#selection_settings' => [ 
      'target_bundles' => array('categories'), 
    ], 
    '#title' => $this->t('Term Name'), 
    '#description' => $this->t('Enter a Category Vocab Term Name'), 
    '#default_value' => $config->get('term_name') ? \Drupal\taxonomy\Entity\Term::load($config->get('term_name')) : NULL,
  ); 

  $form['page_title'] = array( 
    '#type' => 'entity_autocomplete', 
    '#target_type' => 'node', 
    '#selection_settings' => [ 
      'target_bundles' => array('article'), 
    ], 
    '#title' => $this->t('Page Titles'), // 改成复数更贴合多值场景
    '#description' => $this->t('Enter multiple Page Titles (separate with commas or use autocomplete to add)'), 
    '#multiple' => TRUE, // 核心属性:开启多值支持
    '#size' => 60, // 可选:扩大输入框宽度,方便多值输入
    '#default_value' => $config->get('page_title') ? \Drupal\node\Entity\Node::loadMultiple($config->get('page_title')) : [],
  ); 

  return $form;
}

关键改动说明:

  • #multiple => TRUE:这是开启多值的核心配置,告诉Drupal这个字段可以接受并存储多个实体ID
  • 调整标题:把原来的Page Title ($i)改成Page Titles,更符合多值字段的语义
  • 默认值处理:多值字段的默认值需要是实体对象数组,所以用loadMultiple来加载配置中保存的多个节点ID对应的实体
  • 可选的#size:扩大输入框宽度,让用户在输入多个值时体验更好

另外别忘了在提交表单的方法里,要正确保存多值数据,示例如下:

public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);
  
  $this->config('category_dynamic_block.settings')
    ->set('section_title', $form_state->getValue('section_title'))
    ->set('term_name', $form_state->getValue('term_name'))
    ->set('page_title', $form_state->getValue('page_title')) // 这里保存的是节点ID数组
    ->save();
}

这样用户就能通过 autocomplete 选择多个文章节点,或者用逗号分隔输入多个节点标题(Drupal的entity_autocomplete多值支持逗号分隔选择)。

内容的提问来源于stack exchange,提问作者Srijeeta Ghosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:52:37