Drupal 7 email fields

Submitted by bas on Tue, 17/12/2013 - 11:20

Sometimes the small tips are the nicest. If you own a smartphone or tablet it can be annoying to enter an email address in a regular textfield. If you fill out a form and select the email field you expect an virtual keyboard layout suited for filling in email addresses, not your default keyboard layout. The simple trick to get this field to behave is to use the HTML5 <input type="email" /> tag. Now the default Drupal 7 Form API only supports regular text inputs. Changing existing forms is actually quite easy, albeit a bit weighty. It only required 2 steps:

  1. install and enable the elements module
  2. write a hook_form_alter() in your custom theme or module to alter the #type property of the form element. (ie, change textfield to emailfield)
Here's an example:
 * Implements hook_form_alter().
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // I hate simplenews but it makes a good example
  if ($form_id == 'simplenews_block_form') {
    $form['mail']['#type'] = 'emailfield';

"Isn't installing the elements module just to change 1 field a bit weighty?" you might ask. Yes, it is quite a hefty solution to a very slim problem. But I believe the elements module offers a universal way forward when extending the default D7 form API. And it seems like it's pretty future proof because it is included in D8 core. So we might as well start using it now.