views:

1199

answers:

1

Is there an easy way to have the form helpers set the tabindex parameter automatically when using form helpers in Rails?

Basically, I don't want to have to manually set the tab index on every form element when building forms (I keep forgetting to update them when I change things). The majority of the forms I write are basically a list of fields. The tab index should be in the order they are defined. Ideally, I would set the initial index in the form_for call and everything else would be handled for me.

Does anyone know how to do this?

+13  A: 

I usually add a method like this to ApplicationHelper

def autotab
  @current_tab ||= 0
  @current_tab += 1
end

Then in my views I make calls to the helper with a :tabindex => autotab like so:

<%= text_field "post", "login",:tabindex => autotab, :value => @login %>

You can also modify all the text_field, check_box, methods one at a time to add the tabindex automatically, by adding something like this to your application helper: (untested but you get the point)

def text_field_with_tabindex(*args)
  options = args.last
  options[:tabindex] = autotab if options.is_a?(Hash) && options[:tabindex].nil?

  text_field_without_tabindex(*args)
end

def self.included(base)
  base.class_eval do
    alias_method_chain :text_field, :tabindex
  end
end

That might be more trouble than it's worth

Daniel Beardsley