AvailableCountriesTrait.php in Address 8
File
src/Plugin/Field/FieldType/AvailableCountriesTrait.php
View source
<?php
namespace Drupal\address\Plugin\Field\FieldType;
use Drupal\address\Event\AddressEvents;
use Drupal\address\Event\AvailableCountriesEvent;
use Drupal\Core\Form\FormStateInterface;
trait AvailableCountriesTrait {
protected static $availableCountries = [];
public static function defaultCountrySettings() {
return [
'available_countries' => [],
];
}
public function countrySettingsForm(array $form, FormStateInterface $form_state) {
$element = [];
$element['available_countries'] = [
'#type' => 'select',
'#title' => $this
->t('Available countries'),
'#description' => $this
->t('If no countries are selected, all countries will be available.'),
'#options' => \Drupal::service('address.country_repository')
->getList(),
'#default_value' => $this
->getSetting('available_countries'),
'#multiple' => TRUE,
'#size' => 10,
];
return $element;
}
public function getAvailableCountries() {
$field_definition = $this
->getFieldDefinition();
$definition_id = spl_object_hash($field_definition);
if (!isset(static::$availableCountries[$definition_id])) {
$available_countries = array_filter($this
->getSetting('available_countries'));
$event_dispatcher = \Drupal::service('event_dispatcher');
$event = new AvailableCountriesEvent($available_countries, $field_definition);
$event_dispatcher
->dispatch(AddressEvents::AVAILABLE_COUNTRIES, $event);
static::$availableCountries[$definition_id] = $event
->getAvailableCountries();
}
return static::$availableCountries[$definition_id];
}
}