With HTML5 comes new <input/> types, which allow for different keyboards on mobile, improving the mobile user experience. However, Drupal by default does not allow for the changing of <input/> types to these new HTML5 types. This tutorial will show how to set up your system to allow for custom input types to be set on any text element.

This tutorial will cover two main steps:

  1. Adding #keyboard_type to form elements for which we want to change the keyboard type
  2. Overriding theme_textfield() to use the #keyboard_type

Step 1: Adding #keyboard_type to form elements

The first thing to do is add #keyboard_type to a form element that we want to change. An example is as follows:

['telephone'] = array
'#type' => 'textfield',
'#title' => t('Phone number'),
'#keyboard_type' => 'tel',

The form element definition is the same as any textfield, however #keyboard_type has been added to the end of the definition.

Step 2: Overriding theme_textfield() to use the #keyboard_type

This next step needs to be done in template.php of the site theme. We will override theme_textfield(), and within this function, check to see if #keyboard_type has been set, and if it has, we will change the input type.

function THEMEKEY_textfield($variables)
$element $variables ['element'];

$element ['#attributes']['type'] = 'text';
element_set_attributes($element, array('id''name''value''size''maxlength'));
_form_set_class($element, array('form-text'));

$extra '';
    if (
$element ['#autocomplete_path'] && drupal_valid_path($element ['#autocomplete_path']))
$element ['#attributes']['class'][] = 'form-autocomplete';

$attributes = array();
$attributes ['type'] = 'hidden';
$attributes ['id'] = $element ['#attributes']['id'] . '-autocomplete';
$attributes ['value'] = url($element ['#autocomplete_path'], array('absolute' => TRUE));
$attributes ['disabled'] = 'disabled';
$attributes ['class'][] = 'autocomplete';
$extra '<input' drupal_attributes($attributes) . ' />';

// The following three lines of code have been added to change the keyboard
    // type if it has been set.
$element['#attributes']['type'] = $element['#keyboard_type'];

$output '<input' drupal_attributes($element ['#attributes']) . ' />';

$output $extra;

Note: As with any theme function override, THEMEKEY needs to be replaced with the actual theme key of your theme.

The above function is nearly identical to theme_textfield(), but with the addition of the following three lines:

$element['#attributes']['type'] = $element['#keyboard_type'];

These three lines check if #keyboard_type has been set, and if it has, the input type is changed accordingly.


Using this code can greatly improve your user experience on mobile devices. Any textfield can have #keyboard_type added to it, and this can be done both in original form definitions, or in hook_form_alter() implementations anywhere on a site.