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.

Comments

Submitted by Charles (not verified) on Mon, 05/01/2015 - 04:45

Was searching for something to explain how the Elements module types worked for ages, thanks for this

Submitted by bas on Tue, 10/02/2015 - 07:48
bas's picture

You're welcome

Submitted by Anonymous (not verified) on Wed, 20/05/2015 - 19:02

Wooow, thanks a lot, I spent hours to figure out how to change the input type to email. :)

Submitted by bas on Fri, 22/05/2015 - 01:43
bas's picture

Glad that helped you out. Thanks for leaving a note.

Submitted by Alexis (not verified) on Tue, 13/10/2015 - 09:46

Thanks !

I have installed elements module and then,
it works with this code :

$form['mail']['#type'] = 'emailfield';

Submitted by bas on Wed, 14/10/2015 - 12:04
bas's picture

Oh, thanks, I see there's a small mistake in my original post. I omitted ['#type']. Cheers Alexis

Submitted by DreamingX (not verified) on Wed, 13/01/2016 - 00:50

form alter should return $form...

Submitted by bas on Wed, 13/01/2016 - 23:22
bas's picture

Passed by reference instead. Thanks for the note.

Add new comment