View source
<?php
namespace Drupal\phone_international\Plugin\Field\FieldWidget;
use Drupal;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Locale\CountryManager;
class PhoneInternationalDefaultWidget extends WidgetBase {
public static function defaultSettings() {
return [
'initial_country' => 'PT',
'geolocation' => FALSE,
] + parent::defaultSettings();
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['value'] = $element + [
'#type' => 'tel',
'#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
'#attributes' => [
'class' => [
'phone_international-number',
],
'data-country' => $this
->getSetting('initial_country'),
'data-geo' => $this
->getSetting('geolocation') ? 1 : 0,
],
'#element_validate' => [
[
$this,
'phoneValidate',
],
],
'#attached' => [
'library' => [
'phone_international/phone_international',
],
],
];
$module_handler = Drupal::service('module_handler');
$module_path = $module_handler
->getModule('phone_international')
->getPath();
$element['#attached']['drupalSettings']['phone_international']['path'] = $module_path;
return $element;
}
public function phoneValidate($element, FormStateInterface $form_state) {
$value = $form_state
->getValue($element['#parents']);
if ($value !== '' && !Drupal::service('phone_international.validate')
->isValidNumber($value)) {
$form_state
->setError($element, t('The %name "%phone_international" is not valid.', [
'%phone_international' => $value,
'%name' => $element['#title'],
]));
}
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = [];
$elements['geolocation'] = [
'#type' => 'checkbox',
'#title' => t('Enable Geolocation'),
'#default_value' => $this
->getSetting('geolocation'),
];
$countries = CountryManager::getStandardList();
$elements['initial_country'] = [
'#type' => 'select',
'#title' => t('Initial Country'),
'#options' => $countries,
'#default_value' => $this
->getSetting('initial_country'),
'#description' => t('Set default selected country to use in phone field.'),
];
return $elements;
}
public function settingsSummary() {
$summary = [];
$geolocation = $this
->getSetting('geolocation');
$summary[] = t('Use Geolocation: @display_label', [
'@display_label' => $geolocation ? t('Yes') : 'No',
]);
if (!$geolocation) {
$summary[] = t('Default selected country: @value', [
'@value' => $this
->getSetting('initial_country'),
]);
}
return $summary;
}
}