Simple Form is a gem to create visual forms in an easy and flexible manner.
Pass a YAAF::Form
object instance to the simple_form_for
helper method.
For example, in a library management system (a pretty minimal one), the form to create books will look like this:
# app/forms/book_form.rb
class BookForm < YAAF::Form
attr_accessor :name, :isbn
def initialize(attributes)
super(attributes)
@models = [book]
end
def book
@book ||= Book.new(name: name, isbn: isbn)
end
end
# app/controllers/books_controller.rb
class BooksController < ApplicationController
def new
@book = BookForm.new
end
end
<%# app/views/books/new.html.erb %>
<%= simple_form_for(@book, method: :post, url: books_path) do |f| %>
<%= f.input :name %>
<%= f.input :isbn %>
<%= f.submit 'Create Book' %>
<% end %>
In order to make use of translations correctly, we should pass an as
value to the simple_form_for
helper method.
<%# app/views/books/new.html.erb %>
<%= simple_form_for(@book, as: :book, ...) do |f| %>
...
So you now can write your translations as:
# app/config/locales/simple_form.en.yml
en:
simple_form:
...
labels:
book:
name: Book Name
isbn: International Standard Book Number
When using the f.submit
helper method from Simple Form, the method model_name
will be used to display the
button’s text. If this is not defined it will display: “Create Book Form”.
You can use a translation directly in the view to avoid overriding this method.
# app/forms/book_form.rb
...
def model_name
Book.model_name
end
...
More info about how Simple Form translates forms here.
Define the persisted?
method in your form object to let Simple Form know if the object is being created or updated.
# app/forms/book_form.rb
...
def persisted?
book.persisted? # Or you can directly make it return false
end
...
Feel free to create an issue and we’ll discuss about it.
YAAF is maintained by Rootstrap with the help of our contributors.