Ruby On Rails integration / Building forms

If you wanted to construct a form using standard components provided by webface_rails, but standard rails form helper or something like simple_form you'd quickly run into issues and find yourself writing a lot of extra options to add the necessary data- attributes. For that reason, webface_rails introduces its own form helper - webface_form, which supports your usual Rails models, has_one/has_many associations, and works very similar to simple_form. Here's a form that uses all of the possible standard component views in a form:

= webface_form @offer do |f|
  = f.text :title, hint: "Short title, 80 characters max", label: "Title"
  = f.textarea :description, hint: "This can be a long story, up to 1000 characters"
  = f.password :password
  = f.hidden :country_id
  = f.numeric :days_active, tabindex: 1
  = f.checkbox :enabled
  = :category, collection: Offer::CATEGORIES  # collection can be Array or Hash
  = :public, collection: ["public", "private"] # collection can be Array or Hash
  = f.submit "Save"

This will generate a nice html with all the right field names (name="offer[field_name]") and will apply the default styles provided by webface_rails. If there are validation errors upon form submission, it will display validation error below each field.

As with define_component helper, you can supply these form field helpes various html attributes to add. There are form-specific attributes worth mentioning though:

  • :label displays a label before the field (or after, if it's a checkbox). If not provided, will attempt to load i18n translation from models.model.field_name.
  • :hint displays a small text below the field, that you can use to explain more details about this field to the user.
  • :tabindex is assigned automatically to each field, so you don't have to specify it, however if you do, all the other tabindexes will be adjusted accordingly and the same index will not be reused.
  • :collection option is used with select and radio fields and is pretty smart. It can take an array, a two-dimensional array, or a hashe as its value and properly generate field names/values from it. For example, all of those would be valid values for this option:
    ["cars", "real_estate", "appliances"]
    [["cars", "Cars"], ["real_estate", "Real estate"], ["appliances", "Appliances"]]
    { cars: "Cars", real_estate: "Real Estate", appliances: "Appliances" }

To learn more about the possible options for each field, we suggest you look at the haml views for standard components.