Search code examples
ruby-on-railsprototypejsscriptaculous

How to use Scriptaculous effects on error messages


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.


Solution

  • 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.