Autocomplete, clearing form values and Drupal form fields

Some browsers like to be helpful and help by remembering certain form fields. I was having a problem with Firefox auto-populating my some of my form fields (specifically field type 'password' and 'password_confirm') in a custom module I wrote.

After some consternation, I referred to our cardboard cutout Han Solo, who helped me to remember a bit more about form options and field auto-completion.

To fix this problem just add an #attribute of 'autocomplete' => 'off', e.g.

<?php
/**
 * Implementation of hook_form()
 */
function mymodule_form() {
	$form['old_password'] = array(
		'#title' => t('Old Password'),
		'#type' => 'textfield',
		'#attributes' => array('autocomplete' =>'off'),
		'#required' => TRUE,
	);
	$form['new_password'] = array(
		'#type' => 'password_confirm',
		'#attributes' => array('autocomplete' =>'off'),
		'#required' => TRUE,
	);
	$form['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
	);
	$form['clear'] = array(
		'#type' => 'button',
		'#value' => t('Clear'),
		'#attributes' => array('onclick' => 'this.form.reset(); return false;'),
	);
	return $form;
}

The example above also includes a nifty way to clear out form fields via javascript in the $form['clear'] element.

Filed under:

Comments

Thx for sharing this script. I have used some of this in my first drupal module, used for theming the user registration page.

Really like your code for clearing a drupal form. This seems to work well apart from clearing the username and email address fields.

Not sure if this is related but I can;t seem to get the autocomplete part to (not) work. Not sure but I guess this is controlled through the use of sessions and the browser. Also when I looked at drupal's fapi I could see no documentation for this although it did mention about autocomplete_path. Is this the same?

http://api.drupal.org/api/drupal/developer--topics--forms_api_reference…

Hi!
I'm a real dummy in these programming things. So I would really appreciate, if anyone could tell me where/in what file I have to put this script...? Thanx alot in advance
-A-

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>, <java>, <php>. The supported tag styles are: <foo>, [foo].
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.

Ready for transformation?