Overview

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:

span class="st0">'telephone''#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.

span class="st0">'element'];
 
	$element ['#attributes']['type'] = 'text''id', 'name', 'value', 'size', 'maxlength''form-text'));
 
	$extra = '''#autocomplete_path''#autocomplete_path''system', 'drupal.autocomplete');
		$element ['#attributes']['class'][] = 'form-autocomplete''type'] = 'hidden';
		$attributes ['id'] = $element ['#attributes']['id'] . '-autocomplete';
		$attributes ['value'] = url($element ['#autocomplete_path''absolute''disabled'] = 'disabled';
		$attributes ['class'][] = 'autocomplete';
		$extra = '<input'' />';
	}
 
	// The following three lines of code have been added to change the keyboard
	// type if it has been set.
'#keyboard_type']))
	{
		$element['#attributes']['type'] = $element['#keyboard_type'];
	}
 
	$output = '<input''#attributes']) . ' />'

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:

span class="st0">'#keyboard_type']))
{
	$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.

Conclusion

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.