Drupal - Address Field Phone, How to Make it Required

Category:

I've been using the Address Field Phone module with the Commerce and Address Field modules to collect a phone number from users during the checkout process.

The client needed the phone number field to be required, and out of the box there doesn't appear to be a configuration option to make the phone number required. With the address field itself, it can be configured to be required, but since the phone number field is an add on to it, the phone number itself is an optional field.

Unfortunately the Address Field Phone module doesn't appear to have configuration options to make the phone number field required, so with a little hook_form_alter() implementation, we can do this ourselves:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_form_checkout') {
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['phone_block']['phone_number']['phone_number']['#required'] = true;
  }
}

The place to put the #required value is buried pretty deep in the form. If the example code above doesn't work for your form, be sure to use dpm($form) to properly locate the property to set.

Do you collect a phone number during checkout on your Drupal Commerce site? If so, what approach(es) do you take?

Comments

I just added a separate phone number field to the customer profile.

It's to specific.

You easily can create an addressfield plugin in order to make phone part mandatory, then you can turn it on in every addressfield settings page:

/**
 * Implements hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($module, $plugin) {
  if ($module == 'addressfield') {
    return 'plugins/' . $plugin;
  }
}

plugins/format/MYMODULE_PLUGIN.inc:

$plugin = array(
  'title' => t('Musthave phone'),
  'format callback' => 'MYMODULE_PLUGIN_generate',
  'type' => 'address',
  'weight' => 100,
);

function MYMODULE_PLUGIN_generate(&$format, $address, $context = array()) {
  //do whatever you want
}

The $format array here is close to the same like in a form_alter, but only contains the part of addressfield.

Here is an advanced example: http://drupalcode.org/project/addressfield_hu.git/blob_plain/refs/heads/7.x-1.x:/plugins/format/addressfield_hu.inc

 

A phone number isn't really part of someone's address, I thought it made more sense just to add a field to the customer billing / customer shipping profile directly. Both are fieldable, with the addressfield as the only field in each profile.

I have used a normal phone/text field added to the customer profile and the Billing information.