View source
<?php
namespace Drupal\address\Element;
use CommerceGuys\Addressing\AddressFormat\AddressFormat;
use CommerceGuys\Addressing\AddressFormat\AddressField;
use Drupal\address\FieldHelper;
use Drupal\address\LabelHelper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
class ZoneTerritory extends FormElement {
public function getInfo() {
$class = get_class($this);
return [
'#available_countries' => [],
'#input' => TRUE,
'#multiple' => FALSE,
'#default_value' => NULL,
'#process' => [
[
$class,
'processTerritory',
],
[
$class,
'processGroup',
],
],
'#element_validate' => [
[
$class,
'validatePostalCodeElements',
],
],
'#pre_render' => [
[
$class,
'preRenderGroup',
],
],
'#after_build' => [
[
$class,
'clearValues',
],
],
'#theme_wrappers' => [
'container',
],
];
}
public static function applyDefaults(array $value) {
$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;
}
}
return $value;
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
$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']);
}
if (is_array($input)) {
$input = self::applyDefaults($input);
if (empty($input['country_code']) && $element['#required']) {
$input['country_code'] = $element['#default_value']['country_code'];
}
}
return is_array($input) ? $input : $element['#default_value'];
}
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'];
$element = [
'#tree' => TRUE,
'#prefix' => '<div id="' . $wrapper_id . '">',
'#suffix' => '</div>',
'#wrapper_id' => $wrapper_id,
] + $element;
$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 (!$element['#required']) {
$element['country_code']['#empty_value'] = '';
}
if (!empty($value['country_code'])) {
$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;
}
protected static function buildSubdivisionElements(array $element, array $value, AddressFormat $address_format) {
$depth = $address_format
->getSubdivisionDepth();
if ($depth === 0) {
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])) {
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],
'#empty_option' => t('- All -'),
];
if ($current_depth < $depth) {
$element[$property]['#ajax'] = [
'callback' => [
get_called_class(),
'ajaxRefresh',
],
'wrapper' => $element['#wrapper_id'],
];
}
$current_depth++;
}
return $element;
}
protected static function buildPostalCodeElements(array $element, array $value, AddressFormat $address_format) {
if (!in_array(AddressField::POSTAL_CODE, $address_format
->getUsedFields())) {
return $element;
}
$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) . ']';
$element['included_postal_codes'] = [
'#type' => 'textarea',
'#title' => t('Included postal codes'),
'#description' => t('A regular expression ("/(35|38)[0-9]{3}/") or comma-separated list, including ranges ("98, 100:200")'),
'#default_value' => $value['included_postal_codes'],
'#rows' => 1,
'#states' => [
'visible' => [
':input[name="' . $checkbox_path . '"]' => [
'checked' => TRUE,
],
],
],
];
$element['excluded_postal_codes'] = [
'#type' => 'textarea',
'#title' => t('Excluded postal codes'),
'#description' => t('A regular expression ("/(35|38)[0-9]{3}/") or comma-separated list, including ranges ("98, 100:200")'),
'#default_value' => $value['excluded_postal_codes'],
'#rows' => 1,
'#states' => [
'visible' => [
':input[name="' . $checkbox_path . '"]' => [
'checked' => TRUE,
],
],
],
];
return $element;
}
public static function validatePostalCodeElements(array $element, FormStateInterface $form_state) {
$value = $form_state
->getValue($element['#parents']);
if (empty($value['limit_by_postal_code'])) {
unset($value['included_postal_codes']);
unset($value['excluded_postal_codes']);
}
unset($value['limit_by_postal_code']);
$form_state
->setValue($element['#parents'], $value);
}
public static function ajaxRefresh(array $form, FormStateInterface $form_state) {
$triggering_element = $form_state
->getTriggeringElement();
return NestedArray::getValue($form, array_slice($triggering_element['#array_parents'], 0, -2));
}
public static function clearValues(array $element, FormStateInterface $form_state) {
$triggering_element = $form_state
->getTriggeringElement();
if (!$triggering_element) {
return $element;
}
$keys = [
'country_code' => [
'dependent_locality',
'locality',
'administrative_area',
],
'administrative_area' => [
'dependent_locality',
'locality',
],
'locality' => [
'dependent_locality',
],
];
$triggering_element_name = end($triggering_element['#parents']);
if (isset($keys[$triggering_element_name])) {
$input =& $form_state
->getUserInput();
foreach ($keys[$triggering_element_name] as $key) {
if (isset($element[$key])) {
$parents = array_merge($element['#parents'], [
$key,
]);
NestedArray::setValue($input, $parents, '');
$element[$key]['#value'] = '';
}
}
}
return $element;
}
}