Skip to content

Categories:

Location-aware “Cancel” buttons in forms

For a client app, I needed to have “Cancel” buttons in my forms, which would send the user back to the previous page he was on. The restful_authentication plugin generates authenticated_system.rb, which gives us the following methods:

# Store the URI of the current request in the session.
# We can return to this location by calling #redirect_back_or_default.
def store_location
session[:return_to] = request.request_uri
end

# Redirect to the URI stored by the most recent store_location call or
# to the passed default.  Set an appropriately modified
#   after_filter :store_location, :o nly => [:index, :new, :show, :edit]
# for any controller you want to be bounce-backable.
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end

I stored the previous page’s URL in session, and added an after filter in application.rb:

after_filter :store_location, :except => [ :new, :edit ]

In my form, I have two buttons:

#  View - form has a cancel button
= submit_tag 'Cancel', :name => 'cancel_button'
= submit_tag 'Save', :disabled => false, :disable_with => "Please wait..."

In my controller, I just check if params[:cancel_button] is not nil (send the user back to the stored uri in session if so, otherwise process the form):

def create
if params[:cancel_button]
redirect_back_or_default(dashboard_path)
else
@client = Client.build(params[:client])
if @client.save
flash[:notice] = "Client saved."
redirect_to client_url(@client)
else
flash[:error] = "Client not saved."
render :action => "new"
end
end
end

Posted in Tutorials. Tagged with .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.