function country_field_widget_country_default_form_alter in Country 8
Implements hook_field_widget_WIDGET_TYPE_form_alter().
File
- ./
country.module, line 28 - Defines simple country field type.
Code
function country_field_widget_country_default_form_alter(&$element, FormStateInterface $form_state, $context) {
$country =& $element['value'];
$country_code = '';
if (!empty($country['#default_value'])) {
return FALSE;
}
if (!\Drupal::moduleHandler()
->moduleExists('ip2country')) {
return FALSE;
}
if (\Drupal::currentUser()
->isAuthenticated()) {
$uid = \Drupal::currentUser()
->id();
$user_data = \Drupal::service('user.data')
->get('ip2country', $uid);
if (isset($user_data)) {
$country_code = $user_data['country_iso_code_2'];
}
}
else {
$ip = \Drupal::request()
->getClientIp();
$country_code = \Drupal::service('ip2country.manager')
->getCountry($ip);
}
if (in_array($country_code, array_keys($country['#options']))) {
$country['#default_value'] = $country_code;
}
}