Modify address widget to prioritise postcode

Created on 10 April 2025, 16 days ago

When using geo_entity to gather address information, ergo a geocoder to autocomplete the address, it makes sense for the postcode field to be at the top of the address widget so that the geolocation process is "narrowing down" the geographic options as it were (see pic)

This code will sit in a custom module and do that, and changes the text of the field back to a saner version ;)

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_inline_entity_form_entity_form_alter().
 *
 * See: https://git.drupalcode.org/project/inline_entity_form/-/blob/3.x/inline_entity_form.api.php
 */
function MYMODULE_inline_entity_form_entity_form_alter(array &$form, FormStateInterface &$form_state) {
  if ($form['#entity_type'] === 'geo_entity' && $form['#bundle'] === 'address') {  // specifically target the 'address' bundle
    $form['postal_address']['widget'][0]['#after_build'][] = _MYMODULE_customise_address';
  }
}

function _MYMODULE_customise_address($element, $form_state) {
  // Move postcode field to top of fields, and alter text from default.
  $element['address']['postal_code']['#weight'] = -10;  // move field to top
  $element['address']['postal_code']['#title'] = t('Postcode'); // change text to Blighty what what
  return $element;
}

Feature request
Status

Active

Version

1.0

Component

Code

Created by

🇬🇧United Kingdom niklp Nottingham

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @niklp
  • 🇬🇧United Kingdom niklp Nottingham

    In terms of moving this into the module, it would probably require a bit of extra config form wrapping, so you could select which content bundles you want to do this for, but this only targets the form and the likelihood of many geo entity types is low, so it's likely to be a one-hit sitewide thing anyway.

Production build 0.71.5 2024