Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::massageFormValues()
Overrides WidgetBase::massageFormValues
public function massageFormValues(array $values, array $form, array &$form_state) {
// Autocomplete widgets do not send their tids in the form, so we must detect
// them here and process them independently.
$items = array();
$field = $this->field;
// Collect candidate vocabularies.
foreach ($field['settings']['allowed_values'] as $tree) {
if ($vocabulary = entity_load('taxonomy_vocabulary', $tree['vocabulary'])) {
$vocabularies[$vocabulary
->id()] = $vocabulary;
}
}
// Translate term names into actual terms.
foreach ($values as $value) {
// See if the term exists in the chosen vocabulary and return the tid;
// otherwise, create a new term.
if ($possibilities = entity_load_multiple_by_properties('taxonomy_term', array(
'name' => trim($value),
'vid' => array_keys($vocabularies),
))) {
$term = array_pop($possibilities);
$item = array(
'tid' => $term
->id(),
);
}
else {
$vocabulary = reset($vocabularies);
$term = entity_create('taxonomy_term', array(
'vid' => $vocabulary
->id(),
'name' => $value,
));
$item = array(
'tid' => 0,
'entity' => $term,
);
}
$items[] = $item;
}
return $items;
}