Drupal 8 - 自定义字段插件&特定分类词汇

时间:2018-04-20 18:25:57

标签: plugins drupal taxonomy fieldtype

我正在Drupal 8中构建一个自定义复合字段。我几乎就在那里,但我遗漏了最后一点:当我将这个新字段类型添加到内容类型时,分类自动完成字段会从每个分类中提取网站上的词汇。

我正在尝试确定如何仅从特定的“plant_parts”词汇表中提取。目前,在我的小部件代码中,我有这个:

$element['plant_component_measured'] = array(
      '#type' => 'entity_autocomplete',
      '#target_type' => 'taxonomy_term',
      '#title' => t('Plant part'),
      '#prefix' => '<table><tr><td>',
      '#suffix' => ' ',
      '#default_value' => isset($items[$delta]->plant_component_measured) ?
      $items[$delta]->plant_component_measured : NULL, 
  );

1 个答案:

答案 0 :(得分:0)

您可以使用 STATE CONFIG API保存默认值,并在#selection_settings['target_bundles'] = ['plant_part']中指定分类法类型,如下所示

use Drupal\taxonomy\Entity\Term;

:
:

if (empty(\Drupal::state()->get('YOUR_MODULE_NAME.plant_component_measured')))
  \Drupal::state()->set('YOUR_MODULE_NAME.plant_component_measured', '');

$entity = Term::load(\Drupal::state()->get('YOUR_MODULE_NAME.plant_component_measured'));
$element['plant_component_measured'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'taxonomy_term',
  '#title' => $this->t('Plant part'),
  '#description' => $this->t('Plant part'),
  '#prefix' => '<table><tr><td>',
  '#suffix' => ' ',
  '#default_value' => $entity,
  '#selection_handler' => 'default',
  '#selection_settings' => [
    'target_bundles' => [
      'plant_part'
    ],
  ],
];