View source
<?php
namespace Drupal\languagefield\Plugin\Field\FieldWidget;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\languagefield\Plugin\Field\FieldType\LanguageItem;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LanguageAutocompleteWidget extends WidgetBase implements ContainerFactoryPluginInterface {
protected $cacheData;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, CacheBackendInterface $cacheData) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
$this->cacheData = $cacheData;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['third_party_settings'], $container
->get('cache.data'));
}
public static function defaultSettings() {
return [
'size' => '60',
'autocomplete_route_name' => 'languagefield.autocomplete',
'placeholder' => '',
] + parent::defaultSettings();
}
public static function validateElement($element, FormStateInterface $form_state) {
if (!($input = $element['#value'])) {
return;
}
$languages = $element['#languagefield_options'];
$langcode = array_search($input, $languages);
if (!empty($langcode)) {
$form_state
->setValueForElement($element, $langcode);
}
else {
$form_state
->setError($element, t('An unexpected language is entered.'));
}
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$item = $items[$delta];
$value = isset($item->value) ? $item->value : NULL;
$item_definition = is_object($item) ? $item : new LanguageItem($items
->getItemDefinition());
$settable_languages = $item_definition
->getSettableOptions();
$possible_languages = $item_definition
->getPossibleOptions();
$element['value'] = $element + [
'#type' => 'textfield',
'#default_value' => isset($possible_languages[$value]) ? $possible_languages[$value] : '',
'#languagefield_options' => $settable_languages,
'#autocomplete_route_name' => $this
->getSetting('autocomplete_route_name'),
'#autocomplete_route_parameters' => [
'entity_type' => $this->fieldDefinition
->get('entity_type'),
'bundle' => $this->fieldDefinition
->get('bundle'),
'field_name' => $this->fieldDefinition
->get('field_name'),
],
'#size' => $this
->getSetting('size'),
'#placeholder' => $this
->getSetting('placeholder'),
'#maxlength' => 255,
'#element_validate' => [
[
get_class($this),
'validateElement',
],
],
];
return $element;
}
}