Generate the markup For the Address Field with PHP

Created on 4 September 2024, 4 months ago

Long story short, I have an auto-complete text field with a callback that will use AJAX to dynamically fill out several fields. I have no problem updating 'textfield' or 'select' type fields. However, I have failed to update the 'address' field. The core issue seems to be that I cannot generate the markup. Here is a highly simplified attempt to generate the markup for the address field:

use Drupal\Core\Render\RendererInterface;
use CommerceGuys\Addressing\AddressFormat\AddressField;
use CommerceGuys\Addressing\AddressFormat\FieldOverride;

// Load the renderer service.
$renderer = \Drupal::service('renderer');

// Preloaded address values.
$address_values = [
    'country_code' => 'AU',
    'address_line1' => '123 Example St',
    'locality' => 'Melbourne',
    'administrative_area' => 'VIC',
    'postal_code' => '3000',
];

// Define the address field render array.
$address_field = [
    '#type' => 'address',
    '#title' => t('Example Address Field'),
    '#default_value' => $address_values,
    '#tree' => TRUE,
    '#description' => t('Enter the address details.'),
    '#field_overrides' => [
        AddressField::ORGANIZATION => FieldOverride::HIDDEN,
        AddressField::ADDRESS_LINE1 => FieldOverride::OPTIONAL,
        AddressField::ADDRESS_LINE2 => FieldOverride::HIDDEN,
        AddressField::FAMILY_NAME => FieldOverride::HIDDEN,
        AddressField::GIVEN_NAME => FieldOverride::HIDDEN,
    ],
    '#available_countries' => ['AU', 'NZ', 'GB', 'CA', 'US', 'HK'],
    '#required' => TRUE,
];

// Render the address field directly.
$rendered_output = $renderer->renderPlain($address_field);

// Print the rendered HTML of the address field.
print '[' . $rendered_output . ']';

However, all it produces is an empty div:
<div></div>

Any suggestions?

💬 Support request
Status

Active

Version

2.0

Component

Code

Created by

🇦🇺Australia brettsh

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

Comments & Activities

  • Issue created by @brettsh
  • 🇦🇺Australia brettsh

    Eventually, I discovered there was a 'change' cmd I could use. So all I needed to dynamically update the field was:

    function my_module_address_ajax_callback(array &$form, FormStateInterface $form_state) {
        $response = new AjaxResponse();
        // Set the individual sub-fields
        $form['my_address']['postal_code']['#value'] = $postal_code;
        ...
        // Trigger a change event on the address field to reformat it.
        $response->addCommand(new InvokeCommand('[id^="edit-my-address"]', 'change'));
        return $response;
    
Production build 0.71.5 2024