Add an Element to a Drupal Addressfield

The Drupal addressfield project provides a form element containing name and address information. The module exposes a widget that neatly groups the input fields.

I've often seen the need to add additional fields within the context of the address field form element. For example, there is an addressfield_phone project which adds phone, extension, mobile, & fax fields to the address field. It is convenient, but the quirky part is that it stores the additional info in a serialized array.

The problem I was solving today involved a node with an address and email field. I wanted the email field to display within the address field form element.

I wanted the email to appear before the company name, so I added it to the organisation_block element of the address field.

<?php
$form['field_address'][LANGUAGE_NONE][0]['organisation_block']['email'] = $form['field_email'][LANGUAGE_NONE][0];
unset($form['field_email'])
?>

In my case, I was working on a custom form, which was loading the node form to programmatically inject elements, so the way I handled assigning the value in the submit hook would be a little different than if you were simply doing this in a hook_form_alter of a node form.

The email field gets added to the contact results, so all you would need to do is re-assign the output of that field, to where it needs to be.

In the case of altering a node form, you could use hook_node_presave() to re-assign the value.

<?php
function MYMODULE_node_presave($node) {
  if ($node->type == 'my_node_type') {
    if (isset($node->field_address[LANGUAGE_NONE][0]['email'])) {
      $node->field_email[LANGUAGE_NONE][0]['value'] = $node->field_address[LANGUAGE_NONE][0]['email'];
      unset($node->field_address[LANGUAGE_NONE][0]['email']);
    }
  }
}
?>