简体   繁体   中英

Ruby on Rails : how to implement Cancel button in form_tag

I have a basic form using the form_tag helper working fine, but I want to add a cancel button, what is the syntax for doing this? I want the cancel button to appear as a button, not a link, then take the user to a different URL (indicating they don't want to submit the form).

TY, Fred

If you mean a reset button, paste the following inside your form:

<%= button_tag "Reset", type: :reset %>

Tested it, it works fine and resets all fields in the form.

If you want to clear/reset the form fields, do what dchacke suggests.

However, I'd generally expect a Cancel button to not clear the form, but to take me away from the form, meaning I don't plan on submitting it.

If you want the latter, I'd just make a link (or button) to the page you want to go to upon cancelling, such as :

=link_to 'Cancel', my_page_path

Or if you want a button:

= button_tag "Cancel", :type => 'button'

Then add this to your controller:

before_filter :check_for_cancel, :only => [:create, :update]

def check_for_cancel
  if params[:commit] == "Cancel"
    redirect_to my_page_path
  end
end

Instead of a submit tag, I would suggest a <button> tag, because the parameter :commit might be localised, thus making it a pain to evaluate in the controller.

A button_tag can have a name/value like any other field, so you can basically create a flag with it.

The following code is what I would use:

in the view:

<%= button_tag t('buttons.cancel'), type: "submit", name: "cancel", value: true %>

in the controller:

before_filter :redirect_cancel, only: [:create, :update]

private

def redirect_cancel
  redirect_to my_page_path if params[:cancel]
end

Much cleaner imho, because you rely on a flag instead of a (potentially) localised display value.

button_to seems a simple way to achieve the same, but it has to be put outside of the form itself, but that can easily be fixed with css.

Also, to solve this in a more generic way (also working for editing nested resources on a resource that has not been persisted yet), you can create a separate form for the cancel that contains all the original values as hidden fields.

Short and easy.

<%= link_to "Cancel", show_page %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM