bootstrap_form icon indicating copy to clipboard operation
bootstrap_form copied to clipboard

Non-nested fields_for

Open ploomans opened this issue 9 years ago • 3 comments
trafficstars

Currently you can use fields_for to create a nested form like this:

<%= bootstrap_form_for @person do |person_form| %> <%= person_form.fields_for @person.address do |address_fields| %> <%= address_fields.text_field :street %> <% end %> <%= person_form.submit %> <% end %>

This way the input :street wil get the name person[address][street]. I would like that it get the name address[street] so not nested inside person

Using the Rails form helper you would do this by changing "person_form.fields_for" to simply "fields_for" (which works like form_for but without the creation of enclosing form tags)

However bootstrap_fields_for or something similar does not seem to exist.

Is there maybe an option you can pass to bootstrap_form_for so that it will not output the form tags?

ploomans avatar Jul 21 '16 13:07 ploomans

Ok, I just solved it by monkey patching it in my app. (I tried to take the next step and include it in the gem and do a pull request but for many edge cases it still doest not work as you would expect)

module BootstrapForm
  module Helper
    def bootstrap_fields_for(object, options = {}, &block)
      options.reverse_merge!({builder: BootstrapForm::FormBuilder})

      options[:html] ||= {}
      options[:html][:role] ||= 'form'

      layout = case options[:layout]
        when :inline
          "form-inline"
        when :horizontal
          "form-horizontal"
      end

      if layout
        options[:html][:class] = [options[:html][:class], layout].compact.join(" ")
      end

      object_name = model_name_from_record_or_class(object).param_key

      temporarily_disable_field_error_proc do
        fields_for(object_name, object, options, &block)
      end
    end
  end
end

ploomans avatar Jul 21 '16 14:07 ploomans

I'm not sure if this helps anyone else but I was able to use

= fields_for @faq, nil, builder: BootstrapForm::FormBuilder do |f|
  = f.text_field :name
  # …

to get the bootstrap styling for the fields without wrapping it in a form

ideasasylum avatar Sep 29 '16 13:09 ideasasylum

@ideasasylum Thanks, your solution worked perfectly 👍

kylefox avatar Feb 08 '19 00:02 kylefox

I am looking at adding a bootstrap_fields_for form helper.

donv avatar Sep 08 '23 13:09 donv