labeled_form_with_errors

A plugin that handles form errors a more gracefully than the Rails default

4
0
Ruby

LabeledFormWithErrors

This plugin adds form builder (block-style) helper methods that handle
errors on fields in a cleaner way than the Rails default.

New helper methods are:

  • labeled_form_for
  • labeled_fields_for
  • labeled_form_remote_for
  • labeled_remote_form_for

When validations cause errors on a model’s fields, LabeledFormWithErrorsBuilder
wraps the generated elements using this Proc (which you can customize in init.rb)

ActionView::Base.field_error_proc = Proc.new{ |input_or_label, instance| “<span class=“form_error”>#{input_or_label}” }

Example

app/models/person.rb

class Person < ActiveRecord::Base
validates_presence_of :name, :age, :gender
validates_numericality_of :age, :message => “must be a number”
validates_length_of :gender, :is => 1, :message => “must be exactly 1 character”
validates_format_of :gender, :with => /[1]$/, :allow_nil => true, :message => “must be m or f”
end

app/views/edit.html.erb

<% labeled_form_for(@person) do |f| %>

<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :age %>
<%= f.text_field :age %>
<%= f.label :gender %>
<%= f.text_field :gender %>
<%= f.submit "Update" %>
<% end %>

Generates:



<span class="form_error"><input id="person_age" name="person[age]" size="30" type="text" /></span>

Copyright © 2008 Cameron Walters, released under the MIT license


  1. mf ↩︎