Archive

Archive for the ‘Programming’ Category

Disabling Firefox Autocomplete in Rails Forms

December 16th, 2008 3 comments
Here’s an annoying little thing that led me to posting this tip today: Firefox has an autocomplete feature that keeps any form fields you’ve edited on a page filled with the same data if you refresh the page.  This is great if you’re say, ordering plane tickets and need to refresh for some reason because everything you’ve changed will still be there once the page reloads. But this feature became a problem for me today while I was working on a project.  The core of the project is that it is a rating system for a series of short data pieces that are randomly loaded each time the page is loaded, with the ability to both edit the data and submit the rating simultaneously.  Therefore, if you were to click refresh on the page, a new random data piece would be loaded.  This is all well and good, but when you throw in the Firefox autocomplete system into the mix, things get all messy. What I found was that if a user was editing a data piece, then for whatever reason clicked refresh, a new data piece would be randomly loaded for the next page load, but the editing fields that had data that was modified in it from before the refresh will still have that same data in those fields.  So you’ve loaded a new data piece, but the old edited data is still in the fields, so if the user now clicks “submit,” that old data is going to overwrite the new data in those fields. That’s bad news when you’re trying to maintain data integrity. So how do you fix it? Well, there is the ability to add to html form objects this piece of code:
autocomplete="off"
This effectively tells Firefox to ignore the caching that it would normally do to set itself up to autocomplete the field if a refresh occurs.  To achieve this same change in Rails, you must add the Ruby version of that code to every form element that you want Firefox to ignore. So to make a text_field form helper have Firefox autocomplete turned off, you would use code like this:
<% form_for @data do |f| %>
 
<%= f.text_field :title, :autocomplete => "off"  %>
 
<%= f.submit "Submit"  %>
 
<% end  %>
To do the same thing for a collection_select helper, you need to add the autocomplete option to the html_options hash that is passed to the helper like this:
<% form_for @data do |f| %>
 
<%= f.collection_select :data_id, Data.find(:all), :id, :value, {}, {:autocomplete => "off"} %>
 
<%= f.submit "Submit"  %>
 
<% end  %>
Hopefully this little tip will help some people out because I know it drove me crazy today as I thought my app was all messed up but it turned out to be the browser.