3

Is there a way to split an a form (using form_for) across two partials? I want to have text boxes in one partial, and my submit button in another.

Lumen
  • 139
  • 11

1 Answers1

4

You can do that as follows:

# _post_form.html.erb
<%= form_for(@post) do |f| %>
 <% @form = f%>
 <%= render 'form_fields'%>
 <%= render 'form_actions'%>
<% end %>

# _form_fields.html.erb
<div class="field">
 <%= @form.label :name %><br />
 <%= @form.text_field :name %>
</div>
<div class="field">
 <%= @form.label :title %><br />
 <%= @form.text_field :title %>
</div>
<div class="field">
 <%= @form.label :content %><br />
 <%= @form.text_area :content %>
</div>

# _form_actions.html.erb
<div class="actions">
  <%= @form.submit %>
</div>
Anand
  • 3,690
  • 4
  • 33
  • 64
  • Worth noting that this will probably only work if the @form is defined before the `<%= @form.submit %>` line is called in the file. I don't believe this would not work if it were the other way round, with the button above the form, as @form would be seen as `Nil` when the page is generated. – Claudiu Jan 25 '23 at 16:09