In Drupal 7, the Address Field module provided developers an easy way to collect complex address information with relative ease. You could simply add the field to your content type and configure which countries you support along with what parts of an address are needed. However, this ease was limited to fieldable entities. If you needed to collect address information somewhere that wasn’t a fieldable entity, you had a lot more work in store for you. Chances are good that the end result would be as few text fields as possible, no validation, and only supporting with a single country. If you were feeling ambitious, maybe you would have provided a select list with the states or provinces provided via a hardcoded array.
During my most recent Drupal 8 project I wanted to collect structured address information outside the context of an entity. Specifically, I wanted to add a section for address and phone number to the Basic Site Settings configuration page. As it turns out, the same functionality you get on entities is now also available to the Form API.
Address Field’s port to Drupal 8 came in the form of a whole new module, the Address module. With it comes a new address
form element. Let’s use that to add a “Site Address” field to the Basic Settings. First we’ll implement hook_form_FORM_ID_alter()
in a custom module’s .module
file:
<br /> use Drupal\Core\Form\FormStateInterface;</p> <p>function MYMODULE_form_system_site_information_settings_alter(&$form, FormStateInterface $form_state) {<br /> // Overrides go here...<br /> }<br />
Don’t forget to add
use Drupal\Core\Form\FormStateInterface;
at the top of your file. Next, we’ll add a details
group and a fieldset
for the address components to go into:<br /> function MYMODULE_form_system_site_information_settings_alter(&$form, FormStateInterface $form_state) {<br /> // Create our contact information section.<br /> $form['site_location'] = [<br /> '#type' => 'details',<br /> '#title' => t('Site Location'),<br /> '#open' => TRUE,<br /> ];</p> <p> $form['site_location']['address'] = [<br /> '#type' => 'fieldset',<br /> '#title' => t('Address'),<br /> ];<br /> }<br />
Once the fieldset is in place, we can go ahead and add the address components. To do that you’ll first need to install the Address module and its dependencies. You’ll also need to add
use CommerceGuys\Addressing\AddressFormat\AddressField;
at the top of the file as we’ll need some of the constants defined there later.<br /> use Drupal\Core\Form\FormStateInterface;<br /> use CommerceGuys\Addressing\AddressFormat\AddressField;</p> <p>function MYMODULE_form_system_site_information_settings_alter(&$form, FormStateInterface $form_state) {<br /> // … detail and fieldset code …</p> <p> // Create the address field.<br /> $form['site_location']['address']['site_address'] = [<br /> '#type' => 'address',<br /> '#default_value' => ['country_code' => 'US'],<br /> '#used_fields' => [<br /> AddressField::ADDRESS_LINE1,<br /> AddressField::ADDRESS_LINE2,<br /> AddressField::ADMINISTRATIVE_AREA,<br /> AddressField::LOCALITY,<br /> AddressField::POSTAL_CODE,<br /> ],<br /> '#available_countries' => ['US'],<br /> ];<br /> }<br />
There’s a few things we’re doing here worth going over. First we set
'#type' => 'address'
, which the Address module creates for us. Next we set a #default_value
for country_code
to US
. That way the United States specific field config is displayed when the page loads.The
#used_fields
key allows us to configure which address information we want to collect. This is done by passing an array of constants as defined in the AddressField
class. The full list of options is:<br /> AddressField::ADMINISTRATIVE_AREA<br /> AddressField::LOCALITY<br /> AddressField::DEPENDENT_LOCALITY<br /> AddressField::POSTAL_CODE<br /> AddressField::SORTING_CODE<br /> AddressField::ADDRESS_LINE1<br /> AddressField::ADDRESS_LINE2<br /> AddressField::ORGANIZATION<br /> AddressField::GIVEN_NAME<br /> AddressField::ADDITIONAL_NAME<br /> AddressField::FAMILY_NAME<br />
Without any configuration, a full address field looks like this when displaying addresses for the United States.
For our example above, we only needed the street address (
ADDRESS_LINE1
and ADDRESS_LINE2
), city (LOCALITY
), state (ADMINISTRATIVE_AREA
), and zip code (POSTAL_CODE
).Lastly, we define which countries we will be supporting. This is done by passing an array of country codes into the
#available_countries
key. For our example we only need addresses from the United States, so that’s the only value we pass in.The last step in our process is saving the information to the Basic Site Settings config file. First we need to add a new submit handler to the form. At the end of our hook, let’s add this:
<br /> function MYMODULE_form_system_site_information_settings_alter(&$form, FormStateInterface $form_state) {<br /> // … detail and fieldset code …</p> <p> // … address field code …</p> <p> // Add a custom submit handler for our new values.<br /> $form['#submit'][] = 'MYMODULE_site_address_submit';<br /> }<br />
Now we’ll create the handler:
<br /> /**<br /> * Custom submit handler for our address settings.<br /> */<br /> function MYMODULE_site_address_submit($form, FormStateInterface $form_state) {<br /> \Drupal::configFactory()->getEditable('system.site')<br /> ->set(‘address’, $form_state->getValue('site_address'))<br /> ->save();<br /> }<br />
This loads our
site_address
field from the submitted values in $form_state
, and saves it to the system.site
config. The exported system.site.yml
file should now look something like:<br /> name: 'My Awesome Site'<br /> mail: test@domain.com<br /> slogan: ''<br /> page:<br /> 403: ''<br /> 404: ''<br /> front: /user/login<br /> admin_compact_mode: false<br /> weight_select_max: 100<br /> langcode: en<br /> default_langcode: en<br /> address:<br /> country_code: US<br /> langcode: ''<br /> address_line1: '123 W Elm St.'<br /> address_line2: ''<br /> locality: Denver<br /> administrative_area: CO<br /> postal_code: '80266'<br /> given_name: null<br /> additional_name: null<br /> family_name: null<br /> organization: null<br /> sorting_code: null<br /> dependent_locality: null<br />
After that, we need to make sure our field will use the saved address as the
#default_value
. Back in our hook, let’s update that key with the following:<br /> function MYMODULE_form_system_site_information_settings_alter(&$form, FormStateInterface $form_state) {<br /> // … detail and fieldset code …</p> <p> // Create the address field.<br /> $form['site_location']['address']['site_address'] = [<br /> '#type' => 'address',<br /> '#default_value' => \Drupal::config('system.site')->get('address') ?? [<br /> 'country_code' => 'US',<br /> ],<br /> '#used_fields' => [<br /> AddressField::ADDRESS_LINE1,<br /> AddressField::ADDRESS_LINE2,<br /> AddressField::ADMINISTRATIVE_AREA,<br /> AddressField::LOCALITY,<br /> AddressField::POSTAL_CODE,<br /> ],<br /> '#available_countries' => ['US'],<br /> ];</p> <p> // … custom submit handler ...<br /> }<br />
Using PHP 7’s null coalesce operator, we either set the default to the saved values or to a sensible fallback if nothing has been saved yet. Putting this all together, our module file should now look like this:
<br /> <?php</p> <p>/<strong><br /> * @file<br /> * Main module file.<br /> */</p> <p>use Drupal\Core\Form\FormStateInterface;<br /> use CommerceGuys\Addressing\AddressFormat\AddressField;</p> <p>/</strong><br /> * Implements hook_form_ID_alter().<br /> <em>/<br /> function MYMODULE_form_system_site_information_settings_alter(&$form, FormStateInterface $form_state) {<br /> // Create our contact information section.<br /> $form['site_location'] = [<br /> '#type' => 'details',<br /> '#title' => t('Site Location'),<br /> '#open' => TRUE,<br /> ];</p> <p> $form['site_location']['address'] = [<br /> '#type' => 'fieldset',<br /> '#title' => t('Address'),<br /> ];</p> <p> // Create the address field.<br /> $form['site_location']['address']['site_address'] = [<br /> '#type' => 'address',<br /> '#default_value' => \Drupal::config('system.site')->get('address') ?? [<br /> 'country_code' => 'US',<br /> ],<br /> '#used_fields' => [<br /> AddressField::ADDRESS_LINE1,<br /> AddressField::ADDRESS_LINE2,<br /> AddressField::ADMINISTRATIVE_AREA,<br /> AddressField::LOCALITY,<br /> AddressField::POSTAL_CODE,<br /> ],<br /> '#available_countries' => ['US'],<br /> ];</p> <p> // Add a custom submit handler for our new values.<br /> $form['#submit'][] = 'MYMODULE_site_address_submit';<br /> }</p> <p>/**<br /> </em> Custom submit handler for our address settings.<br /> */<br /> function MYMODULE_site_address_submit($form, FormStateInterface $form_state) {<br /> \Drupal::configFactory()->getEditable('system.site')<br /> ->set(‘address’, $form_state->getValue('site_address'))<br /> ->save();<br /> }<br />
Lastly we should do some house cleaning in case our module gets uninstalled for any reason. In the same directory as the
MYMODULE.module
file, let’s add a MYMODULE.install
file with the following code:<br /> /**<br /> * Implements hook_uninstall().<br /> */<br /> function MYMODULE_uninstall() {<br /> // Delete the custom address config values.<br /> \Drupal::configFactory()->getEditable('system.site')<br /> ->clear(‘address’)<br /> ->save();<br /> }<br />
That’s it! Now we have a way to provide location information to the global site configuration. Using that data, I’ll be able to display this information elsewhere as text or as a Google Map. Being able to use the same features that Address field types have, I can leverage other modules that display address information or build my own displays, because I now have reliably structured data to work with.