You are here

protected function TaxNumberDefaultWidget::getSelectedCountry in Commerce Core 8.2

Gets the selected country from the parent entity's address field.

Parameters

\Drupal\Core\Entity\FieldableEntityInterface $entity: The parent entity.

array $form: The entity form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

string|null The country code, or NULL if not found.

1 call to TaxNumberDefaultWidget::getSelectedCountry()
TaxNumberDefaultWidget::formElement in modules/tax/src/Plugin/Field/FieldWidget/TaxNumberDefaultWidget.php
Returns the form for a single field widget.

File

modules/tax/src/Plugin/Field/FieldWidget/TaxNumberDefaultWidget.php, line 248

Class

TaxNumberDefaultWidget
Plugin implementation of the 'commerce_tax_number_default' widget.

Namespace

Drupal\commerce_tax\Plugin\Field\FieldWidget

Code

protected function getSelectedCountry(FieldableEntityInterface $entity, array $form, FormStateInterface $form_state) {
  if (!$entity
    ->hasField('address')) {
    return NULL;
  }

  // Priority: 1) Submitted value 2) Entity value 3) Default country.
  $parents = array_merge($form['#parents'], [
    'address',
    0,
    'address',
    'country_code',
  ]);
  $selected_country = NestedArray::getValue($form_state
    ->getUserInput(), $parents);
  if (!$selected_country && !$entity
    ->get('address')
    ->isEmpty()) {

    /** @var \Drupal\address\AddressInterface $address */
    $address = $entity
      ->get('address')
      ->first();
    $selected_country = $address
      ->getCountryCode();
  }
  elseif (!$selected_country && !empty($form['address']['widget'][0]['address'])) {
    $address_element = $form['address']['widget'][0]['address'];
    $selected_country = Country::getDefaultCountry($address_element['#available_countries']);
  }
  return $selected_country;
}