Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Taxonomy form autocomplete, Create taxonomy term field with FAPI

By editor , 26 March, 2018
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());
}

 

 

Tags

  • Drupal 8
  • Code
  • Taxonomy
  • Form
Find Entity using Drupal EntityQuery
Autocomplete function for textfield of Form API

Comments

Plain text

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

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer