Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the default :size from form.text_field method

I see myself writing a lot of :size => nil for f.text_field as so:

<%= f.text_field :street_address, :size => nil %>
<%= f.text_field :post_code, :size => nil %>
<%= f.text_field :city, :size => nil %>

Which is just dumb. Without the :size => nil above, text_field renders an <input> with a size="some number" (usually size="30") which I don't need or want there.

So, how can I implement DRY and make it so that f.text_field would not generate the size=30 or size="some number" attribute by default? This way I can avoid always having to type :size => nil.

like image 864
Darep Avatar asked Jun 28 '26 23:06

Darep


2 Answers

All default field options are stored in one hash. It defaults to the following:

# action_view/helpers/form_helper
DEFAULT_FIELD_OPTIONS = { "size" => 30 }

You can delete "size" from it in an initializer, for example.

ActionView::Helpers::InstanceTag::DEFAULT_FIELD_OPTIONS.delete("size")
like image 197
Simon Perepelitsa Avatar answered Jun 30 '26 15:06

Simon Perepelitsa


Rails extends Object class with with_options method. You can take advantage of it:

<%= form_for :foo do |f| %>
    <% f.with_options :size => nil do |f_nil| %>
        <%= f_nil.text_field :street_address %>
        <%= f_nil.text_field :post_code %>
        <%= f.text_field :city %> <!-- you can use old f here too! -->
    <% end %>
<% end %>

Gives:

<input id="foo_street_address" name="foo[street_address]" type="text" />
<input id="foo_post_code" name="foo[post_code]" type="text" />
<input id="foo_city" name="foo[city]" size="30" type="text" /> <!-- you can use old f here too! -->
like image 20
jdoe Avatar answered Jun 30 '26 13:06

jdoe