class TaxonomyAutocompleteWidget extends WidgetBase {
public function settingsForm(array $form, array &$form_state) {
$element['placeholder'] = array(
'#type' => 'textfield',
'#title' => t('Placeholder'),
'#default_value' => $this
->getSetting('placeholder'),
'#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
);
return $element;
}
public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
$field = $this->field;
$tags = array();
foreach ($items as $item) {
$tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
}
$element += array(
'#type' => 'textfield',
'#default_value' => taxonomy_implode_tags($tags),
'#autocomplete_path' => $this
->getSetting('autocomplete_path') . '/' . $field['field_name'],
'#size' => $this
->getSetting('size'),
'#placeholder' => $this
->getSetting('placeholder'),
'#maxlength' => 1024,
'#element_validate' => array(
'taxonomy_autocomplete_validate',
),
);
return $element;
}
public function massageFormValues(array $values, array $form, array &$form_state) {
$items = array();
$field = $this->field;
foreach ($field['settings']['allowed_values'] as $tree) {
if ($vocabulary = entity_load('taxonomy_vocabulary', $tree['vocabulary'])) {
$vocabularies[$vocabulary
->id()] = $vocabulary;
}
}
foreach ($values as $value) {
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;
}
}