Maintaining degradibility with two submit buttons instead of submit_to_remote, for preview 5
Now sometimes you want multiple possible branches of results from one form, like “save” and “preview”. Yes, you could change the action of the form with some Javascript, based on a button click, but that’s a little clunky, in my opinion, and very non-degradable. Well good old fashioned web 1.0 sorts will be familiar with just using two submit buttons and checking on those, and of course, that’s nice and easy, in rails: http://www.railsdiary.com/diary/two_submit_buttons.
As that linked to post points out, you can be smart and just check for the existence of the name of the input, and not have to worry about matching the value of the button (and thus be tied to the display text of the submit), such as
view:
<%= submit_tag “Save My Stuff”, :name=>"save" >
<= submit_tag “Show me the Preview”, :name=>"preview" %>controller:
if @params[‘save’]"
else
end
Ajaxy 2.0 previews are all the buzz, so you rip out one of those submits and replace it with a submit_to_remote to a separate action. Well, the problem with that is submit_to_remote doesn’t degrade due to using a button instead of a submit. So for now you just attach an onclick with a remote_function callback to your preview submit, instead and point it at your preview action. Remembering of course to cancel the form submission, so you don’t get a non-Ajax submission overriding your remote call. And keep your checks for the ‘preview’ param in the default action of the form, for when people hit the button without Ajax.
To be really clean about it you should use the UJS plugin for Rails and attach your Ajaxing as a behavior. Then wallah, fully functional degraded form and clean XHTML, with functionality extended via external javascript, intead of spaghetti HTML built around javascript. And at this point it’s easy to add an auto-updating preview, with an observer on the text-field.
Of course, I injected at least one bug in the most recent usage of this simple technique, somehow, and am waiting for court3nay to finish some changes so I can get in there and fix it. But the time before (Scribbish theme fix) seemed to work fine.