LanguageAutocompleteTagsWidget.php in Custom Language field 8
File
src/Plugin/Field/FieldWidget/LanguageAutocompleteTagsWidget.php
View source
<?php
namespace Drupal\languagefield\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\Tags;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\languagefield\Plugin\Field\FieldType\LanguageItem;
class LanguageAutocompleteTagsWidget extends LanguageAutocompleteWidget {
public static function validateElement($element, FormStateInterface $form_state) {
if (!($value = $element['#value'])) {
return;
}
$values = [];
$languages = $element['#languagefield_options'];
$input_values = Tags::explode($element['#value']);
foreach ($input_values as $value) {
$langcode = array_search($value, $languages);
if (!empty($langcode)) {
$values[] = [
'value' => $langcode,
];
}
}
if (count($values) === count($input_values)) {
$form_state
->setValueForElement($element, $values);
}
else {
$form_state
->setError($element, t('An unexpected language is entered.'));
}
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$item_definition = new LanguageItem($items
->getItemDefinition());
$possible_languages = $item_definition
->getPossibleOptions();
$values = [];
foreach ($items as $item) {
if (isset($item->value)) {
$values[] = $possible_languages[$item->value];
}
}
$element['value']['#tags'] = TRUE;
$element['value']['#default_value'] = count($values) ? Tags::implode($values) : '';
return $element;
}
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
return $values['value'];
}
}