Taxonomy form autocomplete, Create taxonomy term field with FAPI | Drupal 8

Taxonomy form autocomplete, Create taxonomy term field with FAPI

Submitted by editor on Mon, 03/26/2018 - 11:07
Question

How to create a taxonomy term autocomplete field.

Simple taxonomy autocomplete field.

Example:
$form['tagtest'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'taxonomy_term',
  '#title' => 'Taxonomy Term',
];

Field with default value

Example : Default TID = 1
$form['tagtest'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'taxonomy_term',
  '#title' => 'Taxonomy Term',
  '#default_value' => \Drupal\taxonomy\Entity\Term::load(1),
];

With a selected vocabulary

Example : 'tags'
$form['tagtest'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'taxonomy_term',
  '#title' => 'Taxonomy Term',
  '#selection_settings' => [
    'target_bundles' => ['tags'],
  ],
];

 

Auto create a term if not exist

Example:
$form['tagtest'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'taxonomy_term',
  '#title' => 'Taxonomy Term',
  '#autocreate' => [
    'bundle' => 'tags', // Required. The bundle name for the new entity.
    'uid' => 1, // Optional. The user ID for the new entity
  ],
];

In this case the returned value is not only a string, it can be a Term.
If new term created, you must save it.
Example:
$tag = $form_state->getValue('tagtest');
if (empty($tag)) {
  drupal_set_message("Tag is empty, nothing to do");
}
elseif (is_string($tag)) {
  drupal_set_message("A term selected, tid = $tag");
}
elseif (isset($tag['entity']) && ($tag['entity'] instanceof \Drupal\taxonomy\Entity\Term)) {
  $entity = $tag['entity'];
  $entity->save();
  drupal_set_message("A new term : " . $entity->id() . " : " . $entity->label());
}

 

 

Comments

robertwright

Sat, 08/11/2018 - 12:12

  I got more information about drupal by reading this. Thanks for sharing this one with us. It is good event and gives more thoughtful matter for this things and inspiring things. Since I am a writer I really impressed with the information. If you want writing service, please contact Custom Essay Writing Service one of the best writing services available. The better service that provides detailed and effective information related to educational basis.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.