/classic

Demo of using a Superform in a "classic" Rails app that uses Erb for templating

Primary LanguageRuby

README

This Rails app demonstrates the user of a Superform in Erb.

Simple demo: recreating Rails scaffolding forms

The goal of this demo is to show how a Superform could replace a form generated by Rails scaffolding; thus, the ApplicationForm looks very plain.

# ./app/views/forms/application_form.rb
class ApplicationForm < Superform::Rails::Form
  include Phlex::Rails::Helpers::Pluralize

  def row(component)
    div do
      render component.field.label(style: "display: block;")
      render component
    end
  end

  def around_template(&)
    super do
      error_messages
      yield
      submit
    end
  end

  def error_messages
    if model.errors.any?
      div(style: "color: red;") do
        h2 { "#{pluralize model.errors.count, "error"} prohibited this post from being saved:" }
        ul do
          model.errors.each do |error|
            li { error.full_message }
          end
        end
      end
    end
  end
end

The form for a Post is what you'd expect.

# ./app/views/posts/form.rb
class Posts::Form < ApplicationForm
  def template(&)
    row field(:title).input
    row field(:body).textarea
  end
end

Rendering it from Erb templates is a little different, but also what you'd expect.

<% # ./app/views/posts/edit.html.erb %>
<h1>Editing post</h1>

<%= render Posts::Form.new @post %>

<br>

<div>
  <%= link_to "Show this post", @post %> |
  <%= link_to "Back to posts", posts_path %>
</div>

To unlock the full power of Superform, learn how to extend it with TailwindCSS classes or use it in a component-driven Rails architecture.