ZoneTerritory.php 10.7 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
      '#pre_render' => [
        [$class, 'preRenderGroup'],
      ],
      '#after_build' => [
        [$class, 'clearValues'],
      ],
      '#theme_wrappers' => ['container'],
    ];
  }

  /**
65
66
67
68
69
70
71
   * Ensures all keys are set on the provided value.
   *
   * @param array $value
   *   The value.
   *
   * @return array
   *   The modified value.
72
   */
73
  public static function applyDefaults(array $value) {
74
75
76
77
78
79
80
81
    $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;
82
83
      }
    }
84
85

    return $value;
86
87
  }

88
89
90
91
92
93
94
95
96
97
98
  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    // Ensure both the default value and the input have all keys set.
    // Preselect the default country to ensure it's present in the value.
    $element['#default_value'] = (array) $element['#default_value'];
    $element['#default_value'] = self::applyDefaults($element['#default_value']);
    if (empty($element['#default_value']['country_code']) && $element['#required']) {
      $element['#default_value']['country_code'] = Country::getDefaultCountry($element['#available_countries']);
    }
99
100
101
102
103
104
    if (is_array($input)) {
      $input = self::applyDefaults($input);
      if (empty($input['country_code']) && $element['#required']) {
        $input['country_code'] = $element['#default_value']['country_code'];
      }
    }
105

106
    return is_array($input) ? $input : $element['#default_value'];
107
108
  }

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
  /**
   * 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');
128
    // The #value has the new values on #ajax, the #default_value otherwise.
129
130
131
132
133
134
135
136
137
138
    $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['country_code'] = [
139
      '#type' => 'address_country',
140
      '#title' => t('Country'),
141
      '#available_countries' => $element['#available_countries'],
142
      '#default_value' => $element['#default_value']['country_code'],
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
      '#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],
206
        '#empty_option' => t('- All -'),
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
      ];
      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;
    }

240
241
242
243
244
245
246
247
248
    $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) . ']';

249
    $element['included_postal_codes'] = [
250
      '#type' => 'textarea',
251
252
      '#title' => t('Included postal codes'),
      '#description' => t('A regular expression ("/(35|38)[0-9]{3}/") or comma-separated list, including ranges ("98, 100:200")'),
253
      '#default_value' => $value['included_postal_codes'],
254
      '#rows' => 1,
255
256
257
258
259
      '#states' => [
        'visible' => [
          ':input[name="' . $checkbox_path . '"]' => ['checked' => TRUE],
        ],
      ],
260
261
    ];
    $element['excluded_postal_codes'] = [
262
      '#type' => 'textarea',
263
264
      '#title' => t('Excluded postal codes'),
      '#description' => t('A regular expression ("/(35|38)[0-9]{3}/") or comma-separated list, including ranges ("98, 100:200")'),
265
      '#default_value' => $value['excluded_postal_codes'],
266
      '#rows' => 1,
267
268
269
270
271
      '#states' => [
        'visible' => [
          ':input[name="' . $checkbox_path . '"]' => ['checked' => TRUE],
        ],
      ],
272
273
274
275
276
    ];

    return $element;
  }

277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
  /**
   * 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);
  }

296
297
298
299
300
  /**
   * Ajax callback.
   */
  public static function ajaxRefresh(array $form, FormStateInterface $form_state) {
    $country_element = $form_state->getTriggeringElement();
301
    $address_element = NestedArray::getValue($form, array_slice($country_element['#array_parents'], 0, -2));
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335

    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;
  }

}