You are here

class Country in Address 8

Same name in this branch
  1. 8 src/Element/Country.php \Drupal\address\Element\Country
  2. 8 src/Plugin/views/filter/Country.php \Drupal\address\Plugin\views\filter\Country
  3. 8 src/Plugin/views/sort/Country.php \Drupal\address\Plugin\views\sort\Country
  4. 8 src/Plugin/views/field/Country.php \Drupal\address\Plugin\views\field\Country

Provides a country form element.

Usage example:

$form['country'] = [
  '#type' => 'address_country',
  '#default_value' => 'DE',
  '#available_countries' => [
    'DE',
    'FR',
  ],
];

Plugin annotation

@FormElement("address_country");

Hierarchy

Expanded class hierarchy of Country

7 string references to 'Country'
address.schema.yml in config/schema/address.schema.yml
config/schema/address.schema.yml
Address::processAddress in src/Element/Address.php
Processes the address form element.
CountryItem::propertyDefinitions in src/Plugin/Field/FieldType/CountryItem.php
Defines field item properties.
views.view.address_test_filter_administrative_area.yml in tests/modules/address_test/config/optional/views.view.address_test_filter_administrative_area.yml
tests/modules/address_test/config/optional/views.view.address_test_filter_administrative_area.yml
views.view.address_test_sort_country.yml in tests/modules/address_test/config/optional/views.view.address_test_sort_country.yml
tests/modules/address_test/config/optional/views.view.address_test_sort_country.yml

... See full list

3 #type uses of Country
Address::processAddress in src/Element/Address.php
Processes the address form element.
CountryDefaultWidget::formElement in src/Plugin/Field/FieldWidget/CountryDefaultWidget.php
Returns the form for a single field widget.
ZoneTerritory::processTerritory in src/Element/ZoneTerritory.php
Processes the zone territory form element.

File

src/Element/Country.php, line 22

Namespace

Drupal\address\Element
View source
class Country extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      // List of country codes. If empty, all countries will be available.
      '#available_countries' => [],
      '#input' => TRUE,
      '#multiple' => FALSE,
      '#default_value' => NULL,
      '#process' => [
        [
          $class,
          'processCountry',
        ],
        [
          $class,
          'processGroup',
        ],
      ],
      '#theme_wrappers' => [
        'container',
      ],
    ];
  }

  /**
   * Processes the address_country form element.
   *
   * @param array $element
   *   The form element to process.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   *
   * @return array
   *   The processed element.
   *
   * @throws \InvalidArgumentException
   *   Thrown when #available_countries is malformed.
   */
  public static function processCountry(array &$element, FormStateInterface $form_state, array &$complete_form) {
    if (isset($element['#available_countries']) && !is_array($element['#available_countries'])) {
      throw new \InvalidArgumentException('The #available_countries property must be an array.');
    }
    $full_country_list = \Drupal::service('address.country_repository')
      ->getList();
    $country_list = $full_country_list;
    if (!empty($element['#available_countries'])) {
      $available_countries = $element['#available_countries'];
      if (!empty($element['#default_value'])) {

        // The current country should always be available.
        $available_countries[] = $element['#default_value'];
      }
      $available_countries = array_combine($available_countries, $available_countries);
      $country_list = array_intersect_key($country_list, $available_countries);
    }
    if (empty($element['#default_value']) && $element['#required']) {

      // Fallback to the first country in the list if the default country
      // is empty even though the field is required.
      $element['#default_value'] = key($country_list);
    }
    $element['#tree'] = TRUE;

    // Hide the dropdown when there is only one possible value.
    if (count($country_list) == 1 && $element['#required']) {
      $element['country_code'] = [
        '#type' => 'hidden',
        '#value' => key($available_countries),
      ];
    }
    else {
      $element['country_code'] = [
        '#type' => 'select',
        '#title' => $element['#title'],
        '#title_display' => $element['#title_display'],
        '#description_display' => $element['#description_display'],
        '#options' => $country_list,
        '#default_value' => $element['#default_value'],
        '#required' => $element['#required'],
        '#limit_validation_errors' => [],
        '#attributes' => [
          'class' => [
            'country',
          ],
          'autocomplete' => 'country',
        ],
        '#weight' => -100,
      ];
      if (!$element['#required']) {
        $element['country_code']['#empty_value'] = '';
      }
      if (!empty($element['#ajax'])) {
        $element['country_code']['#ajax'] = $element['#ajax'];
        unset($element['#ajax']);
      }
      if (!empty($element['#description'])) {
        $element['country_code']['#description'] = $element['#description'];
        unset($element['#description']);
      }
    }

    // Remove the 'country_code' level from form state values.
    $element['country_code']['#parents'] = $element['#parents'];
    return $element;
  }

  /**
   * Gets the default country based on the available countries.
   *
   * Used as a helper by parent form elements (Address, ZoneTerritory).
   *
   * @param array $available_countries
   *   The available countries, an array of country codes.
   *
   * @return string
   *   The default country.
   */
  public static function getDefaultCountry(array $available_countries = []) {
    $full_country_list = \Drupal::service('address.country_repository')
      ->getList();
    $country_list = $full_country_list;
    if (!empty($available_countries)) {
      $available_countries = array_combine($available_countries, $available_countries);
      $country_list = array_intersect_key($country_list, $available_countries);
    }
    $default_country = key($country_list);
    return $default_country;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Country::getDefaultCountry public static function Gets the default country based on the available countries.
Country::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
Country::processCountry public static function Processes the address_country form element.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormElement::processAutocomplete public static function Adds autocomplete functionality to elements.
FormElement::processPattern public static function #process callback for #pattern form element property.
FormElement::validatePattern public static function #element_validate callback for #pattern form element property.
FormElement::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElementInterface::valueCallback 15
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. 1
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.