views:

152

answers:

2

I want to use some Scriptaculous effects on error messages.

<% form_for(@page) do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name %>
    <%= f.error_message_on "name" %>

    <%= f.label :content %>
    <%= f.text_field :content %>
    <%= f.error_message_on "content" %>

    <%= f.submit 'Create' %>
<% end %>

My first idea is to put error messages into div tags and use page.visual_effect in the controller. But I don't know how to choose correct divs that will be affected.

<% form_for(@page) do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name %>
    <div id="errorname"><%= f.error_message_on "name" %></div>

    <%= f.label :content %>
    <%= f.text_field :content %>
    <div id="errorcontent"><%= f.error_message_on "content" %></div>

    <%= f.submit 'Create' %>
<% end %>

Or should I put some if conditions into view and call them from there. By the way I don't know how to that. Can't we do something like f.error_message_on "name", :visual_effect => ... Any help will be appreciated.

A: 

Just put your error message in an identifiable element such as:

<div id="bob">error messages here</div>

Then in your javascript you could do something like:

$('bob').blindUp();
tybro0103
+1  A: 

You are on the right track with wrapping in divs, but you can do it this way in the view:

<%= f.error_message_on "name",
      :css_class => "inputError" %>

There are probably many ways to do it. Having the controller return rjs is one way. To be unobtrusive, considered best practice, you would need to include a javascript file that fires the scriptaculous method when the page is loaded. I use the low pro library for unobtrusive javascript. Here is my suggestion:

layout file:

<%= javascript_include_tag :defaults, ‘lowpro’, 'form_behaviors.js' %>

javascript_file_for_form_actions.js:

Event.addBehavior({ 
  '.inputError' : function() {
    this.hide();
    this.blindUp();
  }
});

You could also conditionally load the javascript file using content_for and change your layout file.

View file:

<% content_for(:javascript) do %> <%= javascript_include_tag “form_behaviors” %>
<% end %>

Somewhere in Layout file:

<% yield :javascript %>

You can get a unobtrusive plugin that includes lowpro for you as well. For more information Peepcode has a good pdf about lowpro, as well as some good screencasts on javascript.

coreypurcell
Maybe nitpicking, but what's with the "javascript_file_for_form_actions.js"? Obviously it's a file, obviously it's javascript (due to .js extension), so why repeat those? How about "form_actions.js"?
ScottJ
I just picked it so that it was clear in my explanations. Rather than using comments. I wouldn't actually name it that.
coreypurcell
And it was actually supposed to be edited to form_behaviors.js, which it is in the content_for part. So I'll edit it now.
coreypurcell