Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the html tag and class generated by fields_for?

This is a simple question that I'm kinda ashamed to ask, but I've been banging my head against the wall and navigating through the rails 3 documentation without any success :/

So, here is the thing:

When I use the fields_for helper it wraps the generated fields in a <div class="fields"> ... </div> tag.

so, my code is

<ul class="block-grid two-up">
  <%= f.fields_for :images do |image_builder| %>
    <%= render "images/form", :f => image_builder %>
  <% end %>
</ul>

and the generated html is:

<ul class="block-grid two-up">
  <div class="fields">
    <div>
      <label for="company_images_attributes_0_image"> Image</label>
      <input id="company_images_attributes_0_image" 
             name="company[images_attributes][0][image]" type="file">
    </div>
  </div>
  <div class="fields">
    <div>
      <label for="company_images_attributes_1_image"> Image</label>
      <input id="company_images_attributes_1_image" 
             name="company[images_attributes][1][image]" type="file">
    </div>
  </div>
</ul>

What I want to do is actually change the <div class="fields"> wrapper tag to <li>.

The documentation says you can pass options to the fields_for, but its not clear about what options you can pass, maybe you can change this wrapper tag?

A possibility could be to override a function, kinda like ActionView::Base.field_error_proc when there is an error in the form.

Quick edit: I forgot to mention that I'm using simple_form to generate this form. I tried looking in the simple_form.rb config file for a way to customize this, but I didn't see any way of doing it.

Solution After further investigation, it turns out the form was using the nested_form gem as well to generate the form (not only simple_form). This generator was causing the fields_for to be wrapped in the div tag. Thanks everybody for their suggestions!

like image 589
Hector Villarreal Avatar asked Jan 20 '12 02:01

Hector Villarreal


2 Answers

A cheap solution would be just adding <li> tag into the form like:

<%= f.fields_for :images do |image_builder| %>
 <li><%= render "images/form", :f => image_builder %></li>
<% end %>

I am not sure if you can completely eliminate the div tag by passing some params to field_for. But I think you can change the name of div class or id by passing the html block, like in form_for:

<%= form_for @image, :as => :post, :url => post_image_path, 
   :html => { :class => "new_image", :id => "new_image" } do |f| %>
like image 43
Marshall Shen Avatar answered Oct 24 '22 17:10

Marshall Shen


The following disables the wrapper:

f.fields_for :images, wrapper:false do |image_builder|

then you can add your own wrapper in the builder block.

like image 198
lulalala Avatar answered Oct 24 '22 19:10

lulalala