Reputation: 1149
In my application I have a form which has two submits: one is a typical submit button which creates an object and redirects the user to it. The other is intended to act as a "Save and Continue" button which creates the object remotely, displays a success flash, and clears the form without sending the user to a different page.
How might this be implemented? I am roughly familiar with AJAX with jQuery and have a few other forms making use of it across the site, but I cannot find a way to create a hybrid form.
Upvotes: 0
Views: 89
Reputation: 1149
MurifoX's answer was on the right path. Here's something like what I did:
if @model.save
if params[:commit] == "Save"
render js: %(window.location.pathname='#{object_path @object}')
elsif params[:commit] == "Save and Continue"
respond_to do |format|
format.js do
@object = Object.new
render 'new'
end
end
end
end
Basically, the form has remote set to true to respond properly to AJAX requests (jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} is also used). If "Save" is clicked, the browser is redirected via JavaScript to the appropriate page. If "Save and Continue" is clicked, the same _partial.js.erb that is used to load the form to begin with is AJAX'd in again with a new object to clear the form. In the actual code, I also do a flash to show that the new object has been created.
Upvotes: 0
Reputation: 15089
Not a pretty approach but this works. On your create
action in your controller, when you finish saving a record you can put some conditional logic to achieve different redirections like this:
respond_to do |format|
if @model.save
if params[:commit] == "Save"
# Redirect to saved object
elsif params[:commit] == "Save and Continue"
# Redirect to other places
end
end
end
The params[:commit]
stores the string of your submit button, so you can use it to build a hybrid form.
Upvotes: 1