public function TaxonomyAutocompleteWidget::massageFormValues

Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::massageFormValues()

Overrides WidgetBase::massageFormValues

File

drupal/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/field/widget/TaxonomyAutocompleteWidget.php, line 73
Definition of Drupal\taxonomy\Plugin\field\widget\TaxonomyAutocompleteWidget.

Class

TaxonomyAutocompleteWidget
Plugin implementation of the 'taxonomy_autocomplete' widget.

Namespace

Drupal\taxonomy\Plugin\field\widget

Code

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.
  $terms = array();
  $field = $this->field;

  // Collect candidate vocabularies.
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      $vocabularies[$vocabulary->vid] = $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 'autocreate' term for insert/update.
    if ($possibilities = entity_load_multiple_by_properties('taxonomy_term', array(
      'name' => trim($value),
      'vid' => array_keys($vocabularies),
    ))) {
      $term = array_pop($possibilities);
    }
    else {
      $vocabulary = reset($vocabularies);
      $term = array(
        'tid' => 'autocreate',
        'vid' => $vocabulary->vid,
        'name' => $value,
        'vocabulary_machine_name' => $vocabulary->machine_name,
      );
    }
    $terms[] = (array) $term;
  }
  return $terms;
}