Skip to content

Repository files navigation

Superform

The best Rails form library. Whether you're using ERB, HAML, or Phlex, Superform makes building forms delightful.

  • No more strong parameters headaches. Add a field to your form and it automatically gets permitted. Never again wonder why your new field isn't saving. Superform handles parameter security for you.

  • Works beautifully with ERB. Start using Superform in your existing Rails app without changing a single ERB template. All the power, zero migration pain.

  • Concise field helpers.Field(:publish_at).date, Field(:email).email, Field(:price).number — intuitive methods that generate the right input types with proper validation.

  • RESTful controller helpers Superform's save and save! methods work exactly like ActiveRecord, making controller code predictable and Rails-like.

Superform is a complete reimagining of Rails forms, built on solid Ruby foundations with modern component architecture under the hood.

MaintainabilityRuby

Video course

Support this project and become a Superform pro by ordering the Phlex on Rails video course.

Installation

Add to the Rails application's Gemfile by executing:

$ bundle add superform

Then install it.

$ rails g superform:install

This will install both Phlex Rails and Superform.

Usage

Start with inline forms in your ERB templates

Superform works instantly in your existing Rails ERB templates. Here's what a form for a blog post might look like:

<!-- app/views/posts/new.html.erb --><h1>New Post</h1><%=renderComponents::Form.new@postdoit.Field(:title).textit.Field(:body).textareait.Field(:publish_at).dateit.Field(:featured).checkboxit.submit"Create Post"end%>

The form automatically generates proper Rails form tags, includes CSRF tokens, and handles validation errors.

Notice anything missing? Superform doesn't need <% %> tags around every single line, unlike all other Rails form helpers.

Extract inline forms to dedicated classes to use in other views

You probably want to use the same form for creating and editing resources. In Superform, you extract forms into their own Ruby classes right along with your views.

# app/views/posts/form.rbclassViews::Posts::Form < Components::Formdefview_templateField(:title).textField(:body).textarea(rows: 10)Field(:publish_at).dateField(:featured).checkboxsubmitendend

Then render this in your views:

<!-- app/views/posts/new.html.erb --><h1>New Post</h1><%=renderViews::Posts::Form.new@post%>

Cool, but you're about to score a huge benefit from extracting forms into their own Ruby classes with automatic strong parameters.

Automatically permit strong parameters with form classes

Include Superform::Rails::StrongParameters in your controllers for automatic parameter handling:

classPostsController < ApplicationControllerincludeSuperform::Rails::StrongParametersdefcreate@post=Post.newifsaveViews::Posts::Form.new(@post)redirect_to@post,notice: 'Post created!'elserender:new,status: :unprocessable_entityendend# ... other actions ...end

The save method automatically:

  • Permits only the parameters defined in your form
  • Assigns them to your model
  • Attempts to save the model
  • Returns true if successful, false if validation fails

Use save! for the bang version that raises exceptions on validation failure or permit if you want to assign parameters to a model without saving it.

Concise HTML5 form helpers

Superform includes helpers for all HTML5 input types:

classUserForm < Components::Formdefview_templateField(:email).email# type="email"Field(:password).password# type="password"Field(:website).url# type="url"Field(:phone).tel# type="tel"Field(:age).number(min: 18)# type="number"Field(:birthday).date# type="date"Field(:appointment).datetime# type="datetime-local"Field(:favorite_color).color# type="color"Field(:bio).textarea(rows: 5)Field(:terms).checkboxsubmitendend

Works great with Phlex

Superform was built from the ground-up using Phlex components, which means you'll feel right at home using it with your existing Phlex views and components.

classViews::Posts::Form < Components::Formdefview_templatediv(class: "form-section")doh2{"Post Details"}Field(:title).text(class: "form-control")Field(:body).textarea(class: "form-control",rows: 10)enddiv(class: "form-section")doh2{"Publishing"}Field(:publish_at).date(class: "form-control")Field(:featured).checkbox(class: "form-check-input")enddiv(class: "form-actions")dosubmit"Save Post",class: "btn btn-primary"endendend

This gives you complete control over markup, styling, and component composition while maintaining all the strong parameter and validation benefits.

Customization

Superforms are built out of Phlex components. The method names correspond with the HTML tag, its arguments are attributes, and the blocks are the contents of the tag.

When building custom components, follow this convention: positional or named keyword arguments are for component configuration (non-HTML concerns like value:, options:, multiple:), and **kwargs are for HTML attributes that pass through to the rendered element. This keeps the boundary between component logic and HTML clean.

# ./app/components/form.rbclassComponents::Form < Superform::Rails::FormclassMyInput < Superform::Rails::Components::Inputdefview_template(&)divclass: "form-field"doinput(**attributes)endendend# Redefining the base Field class lets us override every field component.classField < Superform::Rails::Form::Fielddefinput(**attributes)MyInput.new(self, **attributes)endend# Here we make a simple helper to make our syntax shorter. Given a field it# will also render its label.deflabeled(component)divclass: "form-row"dorendercomponent.field.labelrendercomponentendenddefsubmit(text)button(type: :submit){text}endend

That looks like a LOT of code, and it is, but look at how easy it is to create forms.

# ./app/views/users/form.rbclassUsers::Form < Components::Formdefview_template(&)labeledField(:name).inputlabeledField(:email).input(type: :email)submit"Sign up"endend

Then render it from Erb.

<%= render Users::Form.new @user %>

Much better!

Customizing radios and checkboxes

radios and checkboxes render sensible defaults out of the box, but you can subclass them to match your design system. Override view_template to change the default markup — the block form still works for one-off customizations.

classComponents::Form < Superform::Rails::FormclassMyRadios < Superform::Rails::Components::Radiosdefview_template(&block)choices.eachdo |choice|
ifblockyieldchoiceelsediv(class: "radio-option")dorenderchoice.build_input(class: "radio-input")label(for: DOM.join(dom.id,choice.index),class: "radio-label")doplainchoice.textendendendendendendclassField < Fielddefradios(*options, **attributes, &block)options=enum_optionsifoptions.empty?MyRadios.new(field,options:, **attributes, &block)endendend

Now every Field(:status).radios in your app gets the custom markup. Individual forms can still pass a block for one-off layouts.

Namespaces & Collections

Superform uses a different syntax for namespacing and collections than Rails, which can be a bit confusing since the same terminology is used but the application is slightly different.

Consider a form for an account that lets people edit the names and email of the owner and users of an account.

classAccountForm < Superform::Rails::Formdefview_template# Account#owner returns a single objectnamespace:ownerdo |owner|
# Renders input with the name `account[owner][name]`owner.Field(:name).text# Renders input with the name `account[owner][email]`owner.Field(:email).emailend# Account#members returns a collection of objectscollection(:members).eachdo |member|
# Renders input with the name `account[members][0][name]`,# `account[members][1][name]`, ...member.Field(:name).input# Renders input with the name `account[members][0][email]`,# `account[members][1][email]`, ...member.Field(:email).input(type: :email)# Member#permissions returns an array of values like# ["read", "write", "delete"].member.field(:permissions).collectiondo |permission|
# Renders input with the name `account[members][0][permissions][]`,# `account[members][1][permissions][]`, ...renderpermission.labeldoplainpermission.value.humanizerenderpermission.checkboxendendendendend

One big difference between Superform and Rails is the collection methods require the use of the each method to enumerate over each item in the collection.

There's three different types of namespaces and collections to consider:

  1. Namespace - namespace(:field_name) is used to map form fields to a single object that's a child of another object. In ActiveRecord, this could be a has_one or belongs_to relationship.

  2. Collection - collection(:field_name).each is used to map a collection of objects to a form. In this case, the members of the account. In ActiveRecord, this could be a has_many relationship.

  3. Field Collection - field(:field_name).collection.each is used when the value of a field is enumerable, like an array of values. In ActiveRecord, this could be an attribute that's an Array type.

Change a form's root namespace

By default Superform namespaces a form based on the ActiveModel model name param key.

classUserForm < Superform::Rails::Formdefview_templaterenderField(:email).inputendendrenderLoginForm.new(User.new)# Renders input with the name `user[email]`renderLoginForm.new(Admin::User.new)# Renders input with the name `admin_user[email]`

To customize the form namespace, like an ActiveRecord model nested within a module, the key method can be overriden.

classUserForm < Superform::Rails::Formdefview_templaterenderField(:email).inputenddefkey"user"endendrenderUserForm.new(User.new)# Renders input with the name `user[email]`renderUserForm.new(Admin::User.new)# This will also render inputs with the name `user[email]`

Form field guide

This example builds a realistic job posting form that demonstrates every field type Superform supports. In practice you'd extract helpers to cut down on render calls, but this keeps things explicit so you can see exactly what's happening.

classJobPostingForm < Components::Formdefview_template# Text input, autofocused.Field(:title).input.focus# HTML5 input helpers pass attributes straight through.Field(:contact_email).email(placeholder: "hiring@company.com",required: true)# Block form for custom layout around a field.field(:description)do |f|
divdorenderf.label{"Describe the role"}renderf.textarea(rows: 6,cols: 80)endend# Select options can be [value, label] pairs, single values, hashes, or nil# for a blank option. Pass nil first to prepend a blank <option></option>.divdoField(:experience_level).labelField(:experience_level).select(nil,["junior","Junior"],["mid","Mid-level"],["senior","Senior"],["lead","Lead"])end# Block form gives full control — optgroups, blank options, etc.divdoField(:category_id).label{"Category"}Field(:category_id).selectdo |s|
s.blank_option{"Select a category..."}Category.grouped_by_department.eachdo |department,categories|
s.optgroup(label: department)dos.options(categories)endendendend# Multiple select for has_many-through or array columns.# Adds the HTML multiple attribute, appends [] to the field name,# and includes a hidden input to handle empty submissions.divdoField(:skill_ids).label{"Required skills"}Field(:skill_ids).select(Skill.select(:id,:name),multiple: true)end# ActiveRecord relations work as select options too.# Choices::Mapper uses the primary key as value and joins remaining# attributes for the label.divdoField(:hiring_manager_id).label{"Hiring manager"}Field(:hiring_manager_id).select(User.select(:id,:first_name,:last_name))end# Boolean checkbox — renders a hidden "0" input so unchecked state# is submitted, just like Rails.divdoField(:remote_friendly).label{"This position is remote-friendly"}Field(:remote_friendly).checkboxend# Radio group auto-detected from a Rails enum.# Given: enum :employment_type, full_time: 0, part_time: 1, contract: 2# One-liner — renders <label><input type="radio"> Text</label> per choice.Field(:employment_type).radios# Block form — full control over each choice's markup.fieldsetdolegend{"Employment type"}Field(:employment_type).radiosdo |choice|
choice.label{choice.inputwhitespaceplainchoice.text# "Full time", "Part time", "Contract"}endend# You can also pass explicit options to override enum detection.# Accepts arrays, single values, hashes, or ActiveRecord relations.# Field(:employment_type).radios("full_time" => "Full-time", ...)# Checkbox groups. Same option formats, same Choice API.# Handles name[], checked state, and unique ids automatically.# One-liner:Field(:benefit_ids).checkboxes([1,"Health insurance"],[2,"Dental & vision"],[3,"401(k)"],[4,"Stock options"])# Block form:fieldsetdolegend{"Benefits"}Field(:benefit_ids).checkboxes([1,"Health insurance"],[2,"Dental & vision"],[3,"401(k)"],[4,"Stock options"])do |choice|
choice.label{choice.inputwhitespaceplainchoice.text}endend# Datalist — free-text input with autocomplete suggestions.# No JavaScript required. The browser handles filtering natively.Field(:time_zone).datalist(*ActiveSupport::TimeZone.all.map(&:name))# File upload (remember to set enctype on the form).divdoField(:job_description_pdf).label{"Upload job description"}Field(:job_description_pdf).file(accept: ".pdf,.doc,.docx")endrenderbutton{"Post Job"}endend

Render it with <%= render JobPostingForm.new(@job_posting) %>. For file uploads, pass enctype: "multipart/form-data" to the form constructor.

Extending Superforms

The best part? If you have forms with a completely different look and feel, you can extend the forms just like you would a Ruby class:

classAdminForm < Components::FormclassAdminInput < Components::Basedefview_template(&)input(**attributes)small{admin_tool_tip_forfield.key}endendclassField < Fielddeftooltip_input(**attributes)AdminInput.new(self, **attributes)endendend

Then, just like you did in your Erb, you create the form:

classAdmin::Users::Form < AdminFormdefview_template(&)labeledField(:name).tooltip_inputlabeledField(:email).tooltip_input(type: :email)submit"Save"endend

Since Superforms are just Ruby objects, you can organize them however you want. You can keep your view component classes embedded in your Superform file if you prefer for everything to be in one place, keep the forms in the app/components/forms/*.rb folder and the components in app/components/forms/**/*_component.rb, use Ruby's include and extend features to modify different form classes, or put them in a gem and share them with an entire organization or open source community. It's just Ruby code!

Automatic strong parameters

Superform eliminates the need to manually define strong parameters. Just include Superform::Rails::StrongParameters in your controllers and use the save, save!, and permit methods:

classPostsController < ApplicationControllerincludeSuperform::Rails::StrongParametersincludeViews::Posts# Standard Rails CRUD with automatic strong parametersdefcreate@post=Post.newifsaveForm.new(@post)redirect_to@post,notice: 'Post created successfully.'elserender:new,status: :unprocessable_entityendenddefupdate@post=Post.find(params[:id])ifsave!Form.new(@post)redirect_to@post,notice: 'Post updated successfully.'elserender:edit,status: :unprocessable_entityendend# For cases where you want to assign params without savingdefpreview@post=Post.newpermitForm.new(@post)# Assigns params but doesn't saverender:previewendend

How it works: Superform automatically permits only the parameters that correspond to fields defined in your form. Attempts to mass-assign other parameters are safely ignored, protecting against parameter pollution attacks.

Available methods:

  • save(form) - Assigns permitted params and saves the model, returns true/false
  • save!(form) - Same as save but raises exception on validation failure
  • permit(form) - Assigns permitted params without saving, returns the model

Comparisons

Rails ships with a lot of great options to make forms. Many of these inspired Superform. The tl;dr:

  1. Rails has a lot of great form helpers. Simple Form and Formtastic both have concise ways of defining HTML forms, but do require frequently opening and closing Erb tags.

  2. Superform is uniquely capable of permitting its own controller parameters, leaving you with one less thing to worry about and test. Additionally it can be extended, shared, and modularized since its Plain' 'ol Ruby, which opens up a world of TailwindCSS form libraries and proprietary form libraries developed internally by organizations.

Rails form helpers

Rails form helpers have lasted for almost 20 years and are super solid, but things get tricky when your application starts to take on different styles of forms. To manage it all you have to cobble together helper methods, partials, and templates. Additionally, the structure of the form then has to be expressed to the controller as strong params, forcing you to repeat yourself.

Here's a checkbox group in Rails vs Superform. In Rails you need to manually wire up the field name with [], track checked state against the model, generate unique ids, and point each label's for attribute at the right input:

<%# Rails: checkbox group for a has_many :benefits association %><fieldset><legend>Benefits</legend><%Benefit.all.eachdo |benefit| %><%=form.check_box:benefit_ids,{multiple: true,checked: form.object.benefit_ids.include?(benefit.id),id: "job_posting_benefit_ids_#{benefit.id}"},benefit.id,nil%><%=form.label:benefit_ids,benefit.name,for: "job_posting_benefit_ids_#{benefit.id}"%><%end%><%end%>
# Superform — one-linerField(:benefit_ids).checkboxes(Benefit.select(:id,:name))# Or with custom markupfieldsetdolegend{"Benefits"}Field(:benefit_ids).checkboxes(Benefit.select(:id,:name))do |choice|
choice.label{choice.inputwhitespaceplainchoice.text}endend

Superform handles the field name (benefit_ids[]), checked state, unique ids, and label targeting automatically. The same pattern works for radio groups with radios(...).

With Superform, you build the entire form with Ruby code, so you avoid the Erb gymnastics and helper method soup that it takes in Rails to scale up forms in an organization.

Simple Form

I built some pretty amazing applications with Simple Form and admire its syntax. It requires "Erb soup", which is an opening and closing line of Erb per line. If you follow a specific directory structure or use their component framework, you can get pretty far, but you'll hit a wall when you need to start putting wrappers around forms or inputs.

https://github.com/heartcombo/simple_form#the-wrappers-api

The API is there, but when you change the syntax, you have to reboot the server to see the changes. UI development should be reflected immediately when the page is reloaded, which is what Superforms can do.

Like Rails form helpers, it doesn't self-permit parameters.

https://www.ruby-toolbox.com/projects/simple_form

Formtastic

Formtastic gives us a nice DSL inside of Erb that we can use to create forms, but like Simple Form, there's a lot of opening and closing Erb tags that make the syntax clunky.

It has generators that give you Ruby objects that represent HTML form inputs that you can customize, but its limited to very specific parts of the HTML components. Superform lets you customize every aspect of the HTML in your form elements.

It also does not permit its own parameters.

https://www.ruby-toolbox.com/projects/formtastic

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To preview example forms in your browser, run:

$ bin/preview

This boots a local Rails server at http://localhost:3000 that displays all forms in the examples/ directory. The server supports hot-reloading, so you can edit forms and refresh the page to see changes.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and the created tag, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/rubymonolith/superform. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Superform project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

About

Build highly customizable HTML forms with Phlex components

Topics

Resources

Code of conduct

Stars

393 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages