You are here

public static function Address::processAddress in Address 8

Processes the address form element.

Parameters

array $element: The form element to process.

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

array $complete_form: The complete form structure.

Return value

array The processed element.

Throws

\InvalidArgumentException Thrown when #used_fields is malformed.

File

src/Element/Address.php, line 156

Class

Address
Provides an address form element.

Namespace

Drupal\address\Element

Code

public static function processAddress(array &$element, FormStateInterface $form_state, array &$complete_form) {

  // Convert #used_fields into #field_overrides.
  if (!empty($element['#used_fields']) && is_array($element['#used_fields'])) {
    $unused_fields = array_diff(AddressField::getAll(), $element['#used_fields']);
    $element['#field_overrides'] = [];
    foreach ($unused_fields as $field) {
      $element['#field_overrides'][$field] = FieldOverride::HIDDEN;
    }
    unset($element['#used_fields']);
  }

  // Validate and parse #field_overrides.
  if (!is_array($element['#field_overrides'])) {
    throw new \InvalidArgumentException('The #field_overrides property must be an array.');
  }
  $element['#parsed_field_overrides'] = new FieldOverrides($element['#field_overrides']);
  $id_prefix = implode('-', $element['#parents']);
  $wrapper_id = Html::getUniqueId($id_prefix . '-ajax-wrapper');

  // The #value has the new values on #ajax, the #default_value otherwise.
  $value = $element['#value'];
  $element = [
    '#tree' => TRUE,
    '#prefix' => '<div id="' . $wrapper_id . '">',
    '#suffix' => '</div>',
    // Pass the id along to other methods.
    '#wrapper_id' => $wrapper_id,
  ] + $element;
  $element['langcode'] = [
    '#type' => 'hidden',
    '#value' => $element['#default_value']['langcode'],
  ];
  $element['country_code'] = [
    '#type' => 'address_country',
    '#title' => t('Country'),
    '#available_countries' => $element['#available_countries'],
    '#default_value' => $element['#default_value']['country_code'],
    '#required' => $element['#required'],
    '#limit_validation_errors' => [],
    '#ajax' => [
      'callback' => [
        get_called_class(),
        'ajaxRefresh',
      ],
      'wrapper' => $wrapper_id,
    ],
    '#weight' => -100,
  ];
  if (!empty($value['country_code'])) {
    $element = static::addressElements($element, $value);
  }
  return $element;
}