在 Drupal 6 中向表单和密码字段添加自动完成属性
许多现代浏览器现在都具有自动完成功能,因此用户可以快速填写详细信息,而无需每次登录时都输入用户名和密码。这可以通过向表单和密码元素添加属性“自动完成”并将其值设置为“关闭”来关闭。
将密码字段(以及包含密码字段的表单)的自动完成属性设置为关闭可以为您的Drupal站点增加一个额外的安全级别。这一点尤其重要,因为如果计算机被盗,它更有可能包含允许访问敏感系统的已保存密码。因此,关闭此功能可能对某些系统有益,尤其是那些具有非常敏感信息的系统。
要将autocomplete属性添加到Drupal6中的登录表单,您需要拦截两个表单。它们是user_login_block和user_login。这可以通过几个简单的hook_form_form-id_alter()函数来完成,这些函数只是将所需的属性添加到表单中。由于这是Drupal6,这些功能需要进入一个模块。
/** * Implementation of hook_form_alter(). * * Set the autocomplete attribute to off on the user_login_block form. */ function MYMODULE_form_user_login_block_alter(&$form, &$form_state) { $form['#attributes']['autocomplete'] = 'off'; } /** * Implementation of hook_form_alter(). * * Set the autocomplete attribute to off on the user_login form. */ function MYMODULE_form_user_login_alter(&$form, &$form_state) { $form['#attributes']['autocomplete'] = 'off'; }
因为不同的浏览器以不同的方式实现自动完成功能,您需要在表单和元素上设置自动完成属性。因此,仅将更改添加到登录表单是不够的,您还必须将属性添加到密码字段。这样做的一种方法是hook_form_alter()在每个表单中的每个元素中创建一个钩子和循环,检查密码字段,但这是一件坏事。
但是,通过创建theme_password()主题覆盖功能,有一种更简单的方法可以做到这一点。每次呈现密码字段时都会运行此函数,然后通过向(添加自动完成属性)添加一行(添加自动完成属性)每个密码字段将包含它。将以下代码添加到template.php主题中的文件中。
/** * Render password input field with autocomplete off. */ function MYTHEME_password($element) { $size = $element['#size'] ? ' size="'. $element['#size'] .'" ' : ''; $maxlength = $element['#maxlength'] ? ' maxlength="'. $element['#maxlength'] .'" ' : ''; //将所有密码元素设置为将自动完成属性设置为“关闭” $element['#attributes']['autocomplete'] = 'off'; _form_set_class($element, array('form-text')); $output = ''; return theme('form_element', $element, $output); }
一切就绪后,您现在会发现您的用户现在必须手动输入密码才能登录。