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