向Drupal窗体API文本字段添加清除按钮
时间:2020-03-05 15:25:28 来源:igfitidea点击:
我们想为任何文本字段提供一个快速清除按钮(类似于移动和平板设备中浏览器的地址列)。
下面的快照可以更好地解释这一点。
其中我们可以看到新闻稿过滤表单中的电子邮件搜索字段。
当我在寻找创建这个的时候,我发现HTML5是一个不错的选择。
我们可以使用"search"输入类型简单地创建它。
正确HTML标签如下所示,
<input type="search"id="edit email"name="email"value=""class="form text">
为了以Drupal的方式创建它,我必须定义一个新的表单API类型。
我的hook_element_info()实现及其相关代码如下,
<?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;
}
?>
现在,在表单API中,我们可以使用与textfield非常相似的#type=>'searchfield'。
当然,可以使用hook_form_alter()将任何textfield更改为searchfield,使其看起来像上面提到的那样。
事实上,作为另一种方法,可以使用hook_theme_registry_alter()简单地重写主题函数theme_textfield(),并使用$element['#attributes']['type']。
如果form builder函数显式设置为"search",则可以使用相同的类型,否则应回退到默认的"text"类型。

