[Nitro] Error Handling and Reloading

Arne Brasseur arne at arnebrasseur.net
Sun Dec 16 04:48:53 EST 2007


Matthew B Gardner schreef:
> Hello --
> 	I've been googling and looking through the rdocs for some time now, and I 
> can't find Nitro's answer to this issue: If someone enters an empty field on 
> Form, reload the page without losing the entered data from the other fields 
> and print the appropriate error message. As far as the reloading (without 
> losing the entered data) goes, I'm really not sure how to do that. However, I 
> found a couple references to error handling, but it's not working as I expect 
> it to from those examples. To keep it simple, here's what I'm trying to do:
>
> template...
> <form>
> 	...
> 	#{flash[:err]}
> 	<input type="text" name="body" size="45" />
> 	...
> </form>
>
> controller...
> def form_foo
> 	obj = request.assign(TestObj.new)
> 	if obj.body,empty?
> 		flash[:err] = "No blank entries!"
> 		# reload the page with the entered data...
> 	...
> end
>
> I've tested the error handling a couple different ways, and I can't get it to 
> print. Hopefully my question is clear enough, but please let me know if it's 
> not.
>
> Thanks for any help,
> Mat
If the same action displays and handles the form I'd just store the 
values in instance variables:

#controller
def foo
  @text, @bla, @bar = %w(text bla bar).map {|w| request[w]}
  ....
end

<!--template-->

<input type="text" name="text" value="#{@text}" size="45" />
<input type="text" name="bla" value="#{@bla}" size="45" />

This requires extra logic to render the right template depending on if 
everything processed fine or not.

If you're using a different action you'll have to redirect back to the 
form if there's an error, but in that case the user's browser makes a 
new request and the data from the previous request is gone, so you'll 
have to store it in the flash.

def handle_form
  if (something_not_ok)
    flash_error "something's not ok"
    flash[:form_data] = %w(text bla bar).map {|w| request[w]}
    redirect :show_form #(or redirect_referrer)
  end
end

def show_form
    flash[:form_data] = NullClass.new #to prevent NoMethodError
  ...
end

<input type="text" name="text" value="#{flash[:form_data]['text']}" size="45" />
<input type="text" name="bla" value="#{flash[:form_data]['bla']}" size="45" />


This is all off the top of my head so the syntax might be a bit off. 
There are two different form helpers in Raw and there could very well be 
some functionality in there to do this kind of stuff. I just don't have 
the time right now to look at it in detail.

(ab)

-- 
Ein Fuchs muß tun, was ein Fuchs tun muß
arne at arnebrasseur.net




More information about the Nitro-general mailing list