✍️
Dev Patterns
  • Dev Patterns: Introduction
  • Drupal 8
    • Form Alter
      • data-twig-suggestion preprocess
      • Address field #after_build
    • Language
      • Language direction classes
      • Set twig variables for languages
      • Get the language direction (PHP)
    • Routes
      • Alter page title based on route
    • Preprocess Page
      • Preprocess users
      • Check if a node has body content and create a variable
    • Preprocess HTML
      • Check node ids and field values in preprocess_html
      • Add a body class based on route
    • General Theming
      • Preprocess Paragraph
      • Paragraph theme hook for a specific field value
      • Field theme hook suggestion based on the entity string
    • Twig
      • Twig include file
      • Twig loops
      • Loop index
    • Page alter
      • Page title theme hook
      • Page content type theme hook
      • Region alter
    • Users
      • Twig user variables
      • User view mode theme hook
    • Fields
      • Replace field name
      • Count number in a multi-value field array
    • Terminal
      • Query block ids for use with twig tweak
      • Check for available updates in terminal
  • Drupal 7
    • Create View modes programtically
    • Node form alter
    • Element Children
Powered by GitBook
On this page

Was this helpful?

  1. Drupal 8
  2. Form Alter

Address field #after_build

It's tricky to get at address fields with a standard form alter. I discovered, you can create an after build function to dig into the nested address field arrays. First create the custom function

/**
 * Implements hook_form_alter().
 */
function dev_patterns_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    // Custom after build for address elements.
    $form['field_address']['widget'][0]['address']['#after_build'][] = '_dev_patterns_register_alter_attr';
  }
}

Next, use the new custom function to alter address fields as you normally would.

/**
 * Implements custom function: _gd_quote_register_alter_attr.
 */
function _dev_patterns_register_alter_attr($element, $form_state) {
  // Alter various elements of the reg form address field.
  $element["address_line1"]["#title"] = t('Address');
  $element["address_line2"]["#title"] = t('Address line 2');
  return $element;
}

Previousdata-twig-suggestion preprocessNextLanguage

Last updated 5 years ago

Was this helpful?