awesome_fields icon indicating copy to clipboard operation
awesome_fields copied to clipboard

A Rails plugin to improve forms. Includes a better FormBuilder and DRYness for form fields.

= Awesome Fields Awesome fields is a plugin that adds an extension to the built-in Rails FormBuilder in the form of a new method, FormBuilder#field. This method magically determines what type of field to display for the corresponding method. It also adds a new form builder, +LinedBuilder+, and related methods, such as lined_form_for and lined_fields_for. Note that JS-related methods are not provided, since generally speaking I don't think Rails's JS helpers should be used (look into a library like LowPro instead).

== Overview of the +field+ method

So let's say you had a model MyModel with a migration that looked oddly like: create_table(:my_model) do |t| t.column 'magic', :string t.column 'number', :integer t.column 'hyperdate', :date t.column 'supertime', :time t.column 'incredidatetime', :datetime end

Then let's say we did this bit of magic: <% form_for :model, @model, :action => 'superplace' do |f| %> <%= f.field :magic %> <%= f.field :number %> <%= f.field :hyperdate %> <%= f.field :supertime %> <%= f.field :incredidatetime %> <% end %> In this situation, you would get two plain text boxes, one date selector, one time selector, and one datetime selector.

What if the `magic' field was really long (i.e., we generated a column with type :text instead of :string)? Then we'd probably prefer a textarea. In this situation, we pass the :long option to the +field+ method: <%= f.field :magic, :long => true %> Different field types may deal with this option differently, and some may ignore it entirely.

== Overview of the +LinedBuilder+

+LinedBuilder+ is a Rails form builder that adds support for labels and pretty error handling to forms. +LinedBuilder+ wraps each input element created by a call to a field helper in a div of CSS class +form_line+. It also gives it a label (by default, this contains the humanized name of the field) and, if an error exists, it provides a nested div within the +form_line+ of CSS class +field_error+ and the div's class is changed to form_line with_errors. More details are below.

A short example now. Assume there are three fields for a model -- number', date', and name'. name' is blank but should not be, and so has an error on it. The ERB code:

<% lined_form_for @model do |f| %> <%= f.field :name %> <%= f.text_field :number %> <%= f.field :date %> <% end %>

Will yield the HTML output:

Name should not be blank.

See the section on +LinedBuilder+ below for more details.

== The +field+ Method

The field method automatically takes care of generating a field of the appropriate type for you in a form. It even takes care of a lot of the magic of collection fields. Some details on the inner workings follow. See also the documentation for the +AwesomeFieldHelpers+ for more information.

=== Field Generation There are two steps to generating the field: first, we determine what type of field to generate, then we generate the actual HTML for it.

There are two ways we use to find the type of field to generate. First, we run the method itself and look for what the class of the object returned is. If we get a nil result from the method, then we use the actual database type as our determiner.

To generate the actual HTML, we call a helper method. For example, if we had a string field, then we would call +string_field+. Since there are already methods for most fields, we simply alias the existing methods to the relevant ones. Sometimes, the mapping isn't one-to-one. For example, in the case of strings, sometimes we'll need to make the field a text area and other times just a simple text field (see the situation where we're using the :long option above). In these cases, we can implement the actual method and have it dispatch to the relevant helper methods.

What if you want to specialize the behavior in one of your builders? Just override the relevant methods! Then there's the other situation -- one where maybe you've serialized an object to the database in YAML form, and you want to display a field for it. Since the returned value from the method will be of your class, we may be unable to resolve that class to an actual field type. In this case, you can either alias in your own helper or implement the relevant method in your own builder. The pattern of the methods called is simply the class name underscored (literally, the result of @object.send(method).class.underscore) followed by +_field+. So Strings go to +string_field+, Dates to +date_field+, and DateTimes to +date_time_field+.

== Collection Fields Basic fields are all well and good, but it'd be nice to be able to automatically generate select boxes based on collection fields, too, and have them behave as expected. Awesome fields makes this easier to a certain extent, as well. First of all, if a field returns a value that responds to the +collect+ method, then the field is assumed to be a collection field (an exception is made for Strings, which do respond to +collect+, but are handled as regular text fields).

Then, we use +collection_select+ to generate the appropriate field (actually, we use +select+, because +collection_select+ doesn't allow us to easily indicate the multiple objects that should be preselected). By default, the +value_method+ used to determine the value for the collection options is +to_param+. If a +text_method+ is not specified, then the +name+ or +to_s+ methods are used (they are attempted in that order).

For +select+, we also need an original collection -- basically, a list of all of the possible values -- to use with the list of selected values. If the objects inside the collection are AR objects, then we take their class and issue a find(:all) on it. If there are no available objects, then we attempt to reflect on the association for the given method to determine the right class. For example, with this call:

f.field :collection_method

If +collection_method+ returned a list of Post objects (or a single Post object), then we issue a Post::find(:all) to determine the full collection (of selected and unselected values). If an empty list is returned, or nil, then we look up the association for the object on +collection_method+ and try to invoke a find(:all) on that class. This guessing can be overridden by passing the :collection option with the desired collection.

Note also that the set of selected items (or the single selected item) can be overridden by providing a collection or object to use instead through the :selected option. If :collection is not provided, the class of this object or of the first item in the list will be used to run the find metnioned above.

You can override both the method used for display text and that used for the option value by passing the +text_method+ and +value_method+ options to the +field+ helper. Further options and HTML options are passed on to +select+, as usual.

=== What About Collections of Non-ActiveRecord Objects? Unfortunately, this convenience comes at a slight price when it comes to collections of non-AR objects. If you want to use +field+ with its collection field magic and you've got, say, integers in the collection, then you'll have to do a bit of extra work and specify both the value and text methods, like so:

f.field :numbers, :value_method => :to_int, :text_method => :to_int

In this case, since we're getting numbers out, we just use the +to_int+ method for both the value and the text.

=== Notes Since Rails will typecast date and datetime fields to the Ruby +Time+ class, these typically won't be recognized appropriately. Currently, the +time_field+ method is implemented to double-check with the database the type that needs to be used. If you implement accessors for the relevant fields to return objects of the appropriate type (see http://www.railsweenie.com/forums/1/topics/936 for an example of how you could do this), then the appropriate methods will be called without the extra level of indirection. Sadly, this specialization means that any Time fields will always have their type checked twice.

Also, the presence of FormBuilder#field does NOT in any way mean the other helpers are not available for use. If the decisions +field+ makes don't float your boat, feel free to put in a direct call to the regular helpers. The purpose of +field+ is to try and reduce the repetition (it's a already a string, why say it again?), not to get in your way. If it's getting in your way, you probably need a different solution.

== The +LinedBuilder+ Class

+LinedBuilder+ is meant to take the pain out of creating forms whose fields fit on multiple lines and whose fields have labels and correlated errors. By default, Rails's +FormBuilder+ doesn't do this. This builder provides those capabilities transparently.

Because this builder is a self-contained class, the detailed documentation for it is in the AwesomeFields::LinedBuilder documentation. Go get it!

== License and Such

+awesome_fields+ is Copyright (c) 2008 Antonio Salazar Cardozo, released under the MIT license.