Been playing with merb.

One of the helpers I liked in rails was on form validations.  Found
this was real easy to port over, so I thought I'd share.

It doesn't highlight the field with the error, but it gives that same
nice little div on top.

Say I had an articles controller

  def create
    @article = Article.new(params[:article])
    @article.save!
    redirect article_path(@article)
  rescue
    render :action => 'new'
  end

I would catch the activerecord exception there with the rescue

Then in global_helper.rb, I add the error_messages_for method.  This
is taken from rails and stripped of some of its pieces like
content_tag and pluralize.  I'm sure more of it could be cleaned up if
you wanted to.

    def error_messages_for(*params)
      options = params.last.is_a?(Hash) ? params.pop.symbolize_keys : {}
      objects = params.collect {|object_name|
instance_variable_get("@#{object_name}") }.compact
      count   = objects.inject(0) {|sum, object| sum + object.errors.count }
      unless count.zero?
        html = {}
        [:id, :class].each do |key|
          if options.include?(key)
            value = options[key]
            html[key] = value unless value.blank?
          else
            html[key] = 'errorExplanation'
          end
        end
        header_message = "Errors prohibited this
#{(options[:object_name] || params.first).to_s.gsub('_', ' ')} from
being saved"
        error_messages = objects.map {|object|
object.errors.full_messages.map {|msg| "<li>#{msg}</li>" } }

        "<div class=\"errorExplanation\" id=\"errorExplanation\">
          <h2>#{header_message}</h2>
          <p>There were problems with the following fields:</p>
          <ul>
            #{error_messages}
        </div>"
      else
        ''
      end
    end

in your _form.herb, you simply call error_messages_for

<%= error_messages_for 'article' %>
<dl>
        <dt>Title</dt>
        <dd><%= control_for @article, :title, :text %></dd>
        <dt>Intro</dt>
        <dd><%= control_for @article, :intro, :textarea, :rows => 10, :cols
=> 50 %></dd>
        <dt>Body</dt>
        <dd><%= control_for @article, :body, :textarea, :rows => 20, :cols =>
50 %></dd>
</dl>

When you try to save something that fails validation, you get your
nice error div.


        <div class="errorExplanation" id="errorExplanation">
          <h2>Errors prohibited this article from being saved</h2>
          <p>There were problems with the following fields:</p>
          <ul>
            <li>Title can't be blank</li>
        </div>

fun.
_______________________________________________
Merb-devel mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/merb-devel

Reply via email to