cforge-2.0.x-dev/modules/cforge_address/cforge_address.module
modules/cforge_address/cforge_address.module
<?php
use Drupal\cforge_address\Entity\Neighbourhood;
use CommerceGuys\Addressing\AddressFormat\FieldOverride;
/**
* Make a list of of all the neighbourhood entities.
*
* @return Neighbourhood[]
* Both keys and values are the entity label, order alphabetically.
*/
function cforge_list_neighbourhoods() :array {
$hoods = \Drupal::entityTypeManager()->getStorage('neighbourhood')->loadMultiple();
$options = [];
foreach ($hoods as $id => $hood) {
$options[] = $hood->label();
}
sort($options);
return array_combine($options, $options);
}
/**
* Find and replace the neighbourhoods in the database
*
* @param string $from
* @param string $to
*/
function cf_change_neighbourhood($from, $to) {
$affected = \Drupal::database()->update('user__address')
->fields(['address_dependent_locality' => $to])
->condition('address_dependent_locality',$from)
->execute();
\Drupal::messenger()
->addStatus(t('@num addresses updated.', ['@num' => intval($affected)]));
\Drupal::service('cache_tags.invalidator')
->invalidateTags(['user_values', 'user_view']);
}
/**
* Implements hook_migrate_prepare_row().
*/
function cforge_address_migrate_d7_user_prepare_row($row, $source, $migration) {
static $neighbourhoods = [];
if (empty($neighbourhoods)) {
foreach (Neighbourhood::loadMultiple() as $key => $hood) {
$hoods[$hood->label()] = $key;
}
}
$address = $row->getSourceProperty('profile_address');
$old_neighbourhood = $address[0]['dependent_locality'];
if (isset($hoods[$old_neighbourhood])) {
$address[0]['dependent_locality'] = $hoods[$old_neighbourhood];
$row->setSourceProperty('profile_address', $address);
}
}
/**
* Implements hook_field_widget_single_element_WIDGET_TYPE_form_alter().
*
* Reduce the available countries in the address widget;
* Change to a home made element.
*/
function cforge_field_widget_single_element_address_default_form_alter(&$element, $form_state, $context) {
if ($form_state->getFormObject()->getEntity()->getEntityTypeId() == 'user') {
$element['address']['#type'] = 'cforge_user_address';
}
// make no difference...
$element['address']['#field_overrides']['dependentLocality'] = FieldOverride::REQUIRED;
}
