taxonomy_autocomplete_validate

Versions
7
taxonomy_autocomplete_validate($element, &$form_state)

Form element validate handler for taxonomy term autocomplete element.

Code

modules/taxonomy/taxonomy.module, line 1244

<?php
function taxonomy_autocomplete_validate($element, &$form_state) {
  // Autocomplete widgets do not send their tids in the form, so we must detect
  // them here and process them independently.
  if ($tags = $element['#value']) {
    // Collect candidate vocabularies.
    $field = $form_state['complete form']['#fields'][$element['#field_name']]['field'];
    $vids = array();
    foreach ($field['settings']['allowed_values'] as $tree) {
      $vids[] = $tree['vid'];
    }

    // Translate term names into actual terms.
    $typed_terms = drupal_explode_tags($tags);
    $values = array();
    foreach ($typed_terms as $typed_term) {
      // See if the term exists in the chosen vocabulary and return the tid;
      // otherwise, create a new term.
      if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => $vids))) {
        $term = array_pop($possibilities);
      }
      else {
        $vocabulary = taxonomy_vocabulary_load($vids[0]);
        $term = (object) array(
          'vid' => $vids[0],
          'name' => $typed_term,
          'vocabulary_machine_name' => $vocabulary->machine_name,
        );
        taxonomy_term_save($term);
      }
      $values[] = $term->tid;
    }
    $value = options_array_transpose(array('tid' => $values));
  }
  else {
    $value = array();
  }

  form_set_value($element, $value, $form_state);
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.