Created
October 31, 2013 13:46
-
-
Save mrded/7250025 to your computer and use it in GitHub Desktop.
Drupal: Taxonomy terms as autocomplete using form API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function bar_form($form, &$state) { | |
$form['bar'] = array( | |
'#type' => 'textfield', | |
'#title' => t('Bar'), | |
'#autocomplete_path' => 'taxonomy/autocomplete/field_bar_term', // Field name here. | |
'#element_validate' => array('foo_taxonomy_autocomplete_validate'), | |
); | |
return $form; | |
} | |
function bar_form_submit($form, &$state) { | |
//-- | |
$entity->bar[LANGUAGE_NONE] = $values["bar"]; | |
//-- | |
} | |
/** | |
* Form element validate handler for taxonomy term autocomplete element. | |
* | |
* By some reasons field_widget_field() does not load field. | |
* - I guess it because $element['#field_parents'] & $element['#field_name'] are empty. | |
* | |
* @HACK: This validator is basically clone of taxonomy_autocomplete_validate() | |
* - with some changes to load field. | |
* | |
* @see: taxonomy_autocomplete_validate(). | |
*/ | |
function foo_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. | |
$value = array(); | |
if ($tags = $element['#value']) { | |
// Collect candidate vocabularies. | |
$field = field_info_field($element['#name']); //@HACK: is here! | |
$vocabularies = array(); | |
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. | |
$typed_terms = drupal_explode_tags($tags); | |
foreach ($typed_terms as $typed_term) { | |
// See if the term exists in the chosen vocabulary and return the tid; | |
// otherwise, create a new 'autocreate' term for insert/update. | |
if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) { | |
$term = array_pop($possibilities); | |
} | |
else { | |
$vocabulary = reset($vocabularies); | |
$term = array( | |
'tid' => 'autocreate', | |
'vid' => $vocabulary->vid, | |
'name' => $typed_term, | |
'vocabulary_machine_name' => $vocabulary->machine_name, | |
); | |
} | |
$value[] = (array)$term; | |
} | |
} | |
form_set_value($element, $value, $form_state); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you.