View source
<?php
namespace Drupal\country\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
class CountryAutocompleteWidget extends WidgetBase {
public static function defaultSettings() {
return [
'size' => '60',
'autocomplete_route_name' => 'country.autocomplete',
'placeholder' => t('Start typing a country name ...'),
] + parent::defaultSettings();
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$countries = \Drupal::service('country.field.manager')
->getSelectableCountries($this->fieldDefinition);
$element['value'] = $element + [
'#type' => 'textfield',
'#default_value' => isset($items[$delta]->value) && isset($countries[$items[$delta]->value]) ? $countries[$items[$delta]->value] : '',
'#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,
'#selectable_countries' => $countries,
'#element_validate' => [
[
$this,
'validateElement',
],
],
];
return $element;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element = parent::settingsForm($form, $form_state);
$element['size'] = [
'#type' => 'number',
'#title' => t('Size'),
'#default_value' => $this
->getSetting('size'),
'#required' => TRUE,
'#min' => 20,
];
$element['placeholder'] = [
'#type' => 'textfield',
'#title' => t('Placeholder'),
'#default_value' => $this
->getSetting('placeholder'),
];
return $element;
}
public function settingsSummary() {
$summary = [];
$summary[] = t('Size: @size', [
'@size' => $this
->getSetting('size'),
]);
$summary[] = t('Placeholder: @placeholder', [
'@placeholder' => $this
->getSetting('placeholder'),
]);
return $summary;
}
public static function validateElement($element, FormStateInterface $form_state) {
if ($country = $element['#value']) {
$countries = $element['#selectable_countries'];
$iso2 = array_search($country, $countries);
if (!empty($iso2)) {
$form_state
->setValueForElement($element, $iso2);
}
else {
$form_state
->setError($element, t('An unexpected country has been entered.'));
}
}
}
}