knackforge
September 1, 2014
We wanted to have a quick clear button for any text field (similar to address bar of browsers in mobile and tablet devices). Snapshot below might explain it much better. In this you are seeing email search field in newsletter filter form.
While I was in search for creating this, I found HTML5 is as the way to go. One can simply create that by using "search" input type. The proper HTML tag for the same is below,
<input type="search" id="edit-email" name="email" value="" class="form-text">
To create this in Drupal way, I had to define a new Form API type. My hook_element_info() implementation for the same and its related code are below,
<?php
/**
* Implements hook_element_info().
*/
function mymodule_element_info() {
$types = array();
$types['searchfield'] = array(
'#input' => TRUE,
'#autocomplete_path' => FALSE,
'#process' => array('mymodule_process_searchfield'),
'#theme' => 'searchfield',
'#theme_wrappers' => array('form_element'),
);
return $types;
}
/**
* Process function for form type searchfield
*/
function mymodule_process_searchfield($element) {
return $element;
}
/**
* Implements hook_theme()
*/
function mymodule_theme() {
return array(
'searchfield' => array(
'render element' => 'element',
),
);
}
/**
* Theme function for search field.
*/
function theme_searchfield($variables) {
$element = $variables['element'];
$element['#attributes']['type'] = 'search';
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'])) {
drupal_add_library('system', 'drupal.autocomplete');
$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) . ' />';
}
$output = '<input' . drupal_attributes($element['#attributes']) . ' />';
return $output . $extra;
}
?>
Now in your Form API you can make use of #type => 'searchfield' very similar to textfield. Of course, any textfield can be changed to searchfield using hook_form_alter() so it would appear as mentioned above.
In fact, as another approach, one can simply override the theme function theme_textfield() using hook_theme_registry_alter() and make use of $element['#attributes']['type']. If explicitly set by form builder function as 'search' the same can be used, else shall fallback to default 'text' type. It was too late when I realized this :(
Just like how your fellow techies do.
We'd love to talk about how we can work together
Take control of your AWS cloud costs that enables you to grow!