2
votes

I'm building a custom compound field in Drupal 8. I'm almost there, but one final bit I'm missing: when I add this new field type to a content type, the taxonomy autocomplete field pulls from every taxonomy vocabulary on the site.

I'm trying to determine how to only pull from a specific "plant_parts" vocabulary. Currently, within my widget code, I've got this:

$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
actually.. made progress, inserting: '#selection_settings' => array( 'target_bundles' => array('taxonomy_term', 'plant_part'), ),turpentyne

1 Answers

0
votes

You can use STATE or CONFIG API for saving the default value and specify your taxonomy type in #selection_settings['target_bundles'] = ['plant_part'] as below

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'
    ],
  ],
];