ZoneTerritory.php 10.1 KB
Newer Older
1 2 3 4 5
<?php

namespace Drupal\address\Element;

use CommerceGuys\Addressing\AddressFormat\AddressFormat;
6
use CommerceGuys\Addressing\AddressFormat\AddressField;
7 8 9 10
use Drupal\address\FieldHelper;
use Drupal\address\LabelHelper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;
11 12
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
13 14 15 16

/**
 * Provides a zone territory form element.
 *
17 18
 * Use it to populate a \CommerceGuys\Addressing\Zone\ZoneTerritory object.
 *
19 20 21
 * Usage example:
 * @code
 * $form['territory'] = [
22
 *   '#type' => 'address_zone_territory',
23 24 25 26 27 28 29 30
 *   '#default_value' => [
 *     'country_code' => 'US',
 *     'administrative_area' => 'CA',
 *     'included_postal_codes' => '94043',
 *   ],
 * ];
 * @endcode
 *
31
 * @FormElement("address_zone_territory")
32 33 34 35 36 37 38 39 40
 */
class ZoneTerritory extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
41 42 43
      // List of country codes. If empty, all countries will be available.
      '#available_countries' => [],

44 45 46 47 48 49 50
      '#input' => TRUE,
      '#multiple' => FALSE,
      '#default_value' => NULL,
      '#process' => [
        [$class, 'processTerritory'],
        [$class, 'processGroup'],
      ],
51 52 53
      '#element_validate' => [
        [$class, 'validatePostalCodeElements'],
      ],
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
      '#pre_render' => [
        [$class, 'preRenderGroup'],
      ],
      '#after_build' => [
        [$class, 'clearValues'],
      ],
      '#theme_wrappers' => ['container'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if (is_array($input)) {
69
      $value = $input;
70 71 72 73 74
    }
    else {
      if (!is_array($element['#default_value'])) {
        $element['#default_value'] = [];
      }
75 76 77 78 79 80 81 82 83 84 85
      $value = $element['#default_value'];
    }
    // Initialize properties.
    $properties = [
      'country_code',
      'administrative_area', 'locality', 'dependent_locality',
      'included_postal_codes', 'excluded_postal_codes',
    ];
    foreach ($properties as $property) {
      if (!isset($value[$property])) {
        $value[$property] = NULL;
86 87
      }
    }
88 89

    return $value;
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
  }

  /**
   * Processes the zone territory 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 or #used_fields is malformed.
   */
  public static function processTerritory(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $id_prefix = implode('-', $element['#parents']);
    $wrapper_id = Html::getUniqueId($id_prefix . '-ajax-wrapper');
    $value = $element['#value'];
    if (empty($value['country_code']) && $element['#required']) {
113 114
      // Preselect the default country so that the other elements can be shown.
      $value['country_code'] = Country::getDefaultCountry($element['#available_countries']);
115 116 117 118 119 120 121 122 123 124
    }

    $element = [
      '#tree' => TRUE,
      '#prefix' => '<div id="' . $wrapper_id . '">',
      '#suffix' => '</div>',
      // Pass the id along to other methods.
      '#wrapper_id' => $wrapper_id,
    ] + $element;
    $element['country_code'] = [
125
      '#type' => 'address_country',
126
      '#title' => t('Country'),
127
      '#available_countries' => $element['#available_countries'],
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
      '#default_value' => $value['country_code'],
      '#required' => $element['#required'],
      '#limit_validation_errors' => [],
      '#ajax' => [
        'callback' => [get_called_class(), 'ajaxRefresh'],
        'wrapper' => $wrapper_id,
      ],
      '#weight' => -100,
    ];
    if (!$element['#required']) {
      $element['country_code']['#empty_value'] = '';
    }
    if (!empty($value['country_code'])) {
      /** @var \CommerceGuys\Addressing\AddressFormat\AddressFormat $address_format */
      $address_format = \Drupal::service('address.address_format_repository')->get($value['country_code']);
      $element = static::buildSubdivisionElements($element, $value, $address_format);
      $element = static::buildPostalCodeElements($element, $value, $address_format);
    }

    return $element;
  }

  /**
   * Builds the subdivision form elements.
   *
   * @param array $element
   *   The existing form element array.
   * @param array $value
   *   The element value.
   * @param \CommerceGuys\Addressing\AddressFormat\AddressFormat $address_format
   *   The address format for the selected country.
   *
   * @return array
   *   The form with the added subdivision elements.
   */
  protected static function buildSubdivisionElements(array $element, array $value, AddressFormat $address_format) {
    $depth = $address_format->getSubdivisionDepth();
    if ($depth === 0) {
      // No predefined data found.
      return $element;
    }

    $labels = LabelHelper::getFieldLabels($address_format);
    $subdivision_fields = $address_format->getUsedSubdivisionFields();
    $current_depth = 1;
    $parents = [];
    foreach ($subdivision_fields as $index => $field) {
      $property = FieldHelper::getPropertyName($field);
      $parent_property = $index ? FieldHelper::getPropertyName($subdivision_fields[$index - 1]) : 'country_code';
      if ($parent_property && empty($value[$parent_property])) {
        // No parent value selected.
        break;
      }
      $parents[] = $value[$parent_property];
      $subdivisions = \Drupal::service('address.subdivision_repository')->getList($parents);
      if (empty($subdivisions)) {
        break;
      }

      $element[$property] = [
        '#type' => 'select',
        '#title' => $labels[$field],
        '#options' => $subdivisions,
        '#default_value' => $value[$property],
192
        '#empty_option' => t('- All -'),
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
      ];
      if ($current_depth < $depth) {
        $element[$property]['#ajax'] = [
          'callback' => [get_called_class(), 'ajaxRefresh'],
          'wrapper' => $element['#wrapper_id'],
        ];
      }

      $current_depth++;
    }

    return $element;
  }

  /**
   * Builds the postal code form elements.
   *
   * @param array $element
   *   The existing form element array.
   * @param array $value
   *   The element value.
   * @param \CommerceGuys\Addressing\AddressFormat\AddressFormat $address_format
   *   The address format for the selected country.
   *
   * @return array
   *   The form with the added postal code elements.
   */
  protected static function buildPostalCodeElements(array $element, array $value, AddressFormat $address_format) {
    if (!in_array(AddressField::POSTAL_CODE, $address_format->getUsedFields())) {
      // The address format doesn't use a postal code field.
      return $element;
    }

226 227 228 229 230 231 232 233 234
    $element['limit_by_postal_code'] = [
      '#type' => 'checkbox',
      '#title' => t('Limit by postal code'),
      '#default_value' => !empty($value['included_postal_codes']) || !empty($value['excluded_postal_codes']),
    ];
    $checkbox_parents = array_merge($element['#parents'], ['limit_by_postal_code']);
    $checkbox_path = array_shift($checkbox_parents);
    $checkbox_path .= '[' . implode('][', $checkbox_parents) . ']';

235 236
    $element['included_postal_codes'] = [
      '#type' => 'textfield',
237 238
      '#title' => t('Included postal codes'),
      '#description' => t('A regular expression ("/(35|38)[0-9]{3}/") or comma-separated list, including ranges ("98, 100:200")'),
239
      '#default_value' => $value['included_postal_codes'],
240 241 242 243 244
      '#states' => [
        'visible' => [
          ':input[name="' . $checkbox_path . '"]' => ['checked' => TRUE],
        ],
      ],
245 246 247
    ];
    $element['excluded_postal_codes'] = [
      '#type' => 'textfield',
248 249
      '#title' => t('Excluded postal codes'),
      '#description' => t('A regular expression ("/(35|38)[0-9]{3}/") or comma-separated list, including ranges ("98, 100:200")'),
250
      '#default_value' => $value['excluded_postal_codes'],
251 252 253 254 255
      '#states' => [
        'visible' => [
          ':input[name="' . $checkbox_path . '"]' => ['checked' => TRUE],
        ],
      ],
256 257 258 259 260
    ];

    return $element;
  }

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  /**
   * Validates the postal code elements.
   *
   * @param array $element
   *   The existing form element array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public static function validatePostalCodeElements(array $element, FormStateInterface $form_state) {
    $value = $form_state->getValue($element['#parents']);
    if (empty($value['limit_by_postal_code'])) {
      // Remove postal code values if the main checkbox was unchecked.
      unset($value['included_postal_codes']);
      unset($value['excluded_postal_codes']);
    }
    unset($value['limit_by_postal_code']);
    $form_state->setValue($element['#parents'], $value);
  }

280 281 282 283 284
  /**
   * Ajax callback.
   */
  public static function ajaxRefresh(array $form, FormStateInterface $form_state) {
    $country_element = $form_state->getTriggeringElement();
285
    $address_element = NestedArray::getValue($form, array_slice($country_element['#array_parents'], 0, -2));
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319

    return $address_element;
  }

  /**
   * Clears the country-specific form values when the country changes.
   *
   * Implemented as an #after_build callback because #after_build runs before
   * validation, allowing the values to be cleared early enough to prevent the
   * "Illegal choice" error.
   */
  public static function clearValues(array $element, FormStateInterface $form_state) {
    $triggering_element = $form_state->getTriggeringElement();
    if (!$triggering_element) {
      return $element;
    }

    $triggering_element_name = end($triggering_element['#parents']);
    if ($triggering_element_name == 'country_code') {
      $keys = [
        'dependent_locality', 'locality', 'administrative_area',
      ];
      $input = &$form_state->getUserInput();
      foreach ($keys as $key) {
        $parents = array_merge($element['#parents'], [$key]);
        NestedArray::setValue($input, $parents, '');
        $element[$key]['#value'] = '';
      }
    }

    return $element;
  }

}