global_gateway-8.x-1.x-dev/modules/global_gateway_country/global_gateway_country.module
modules/global_gateway_country/global_gateway_country.module
<?php /** * @file * Basic module file. */ use Drupal\Core\Form\FormStateInterface; /** * Implements hook_field_widget_form_alter(). */ function global_gateway_country_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) { // Prevent country detection for the update/edit node forms // and translations form. $path = \Drupal::service('path.current')->getPath(); if (stripos($path, '/edit') !== FALSE || stripos($path, '/translations') !== FALSE ) { return FALSE; } /** @var \Drupal\Core\Field\FieldItemListInterface $items */ $items = $context['items']; $field_definition = $items->getFieldDefinition(); $settings = $field_definition->getSettings(); $country = &$element['value']; // Don't run detection when current field isn't a country field, // or user set default value for widget. if ($field_definition->getType() != 'country' || empty($settings['preselect_user_region_enabled']) || !empty($country['#default_value']) ) { return FALSE; } // Negotiate the country code. $code = \Drupal::service('global_gateway_region_negotiator') ->negotiateRegion(); // Workaround for the autocomplete widget. if (isset($country['#selectable_countries'])) { /** @var \Drupal\Core\StringTranslation\TranslatableMarkup $value */ $value = $country['#selectable_countries'][$code]; $value = $value->render(); $code = ['value' => $value, 'label' => $value]; } $country['#default_value'] = $code; } /** * Implements hook_field_info_alter(). */ function global_gateway_country_field_info_alter(&$info) { $info['country']['class'] = '\Drupal\global_gateway_country\Plugin\Field\FieldType\CountryItem'; $info['country']['provider'] = 'global_gateway_country'; } /** * Implements hook_form_FORM_ID_alter(). */ function global_gateway_country_form_field_config_edit_form_alter(&$form) { // Move the preselect option checkbox to the default value container. if (\Drupal::routeMatch()->getParameters()->get('field_config')->getType() == 'country') { if (isset($form['settings']) && isset($form['settings']['preselect_user_region_enabled'])) { $element = $form['settings']['preselect_user_region_enabled']; unset($form['settings']['preselect_user_region_enabled']); $form['default_value']['widget'][0]['value']['#states'] = [ 'visible' => [ ':input[name="default_value_input[preselect_user_region_enabled]"]' => [ 'checked' => FALSE, ], ], ]; $form['default_value']['preselect_user_region_enabled'] = $element; $form['actions']['submit']['#submit'][] = [ '\Drupal\global_gateway_country\Plugin\Field\FieldType\CountryItem', 'submitPreselectSetting', ]; } } }