diff --git a/README.md b/README.md index 4a2c4bd..32b3e48 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,44 @@ Then render it from Erb. Much better! +### Namespacing forms + +By default Superform will namespace a form based on the ActiveModel model name param key. + +```ruby +class UserForm < Superform::Rails::Form + def template + render field(:email).input + end +end + +render LoginForm.new(User.new) +# This will render inputs with the name `user[email]` + +render LoginForm.new(Admin::User.new) +# This will render inputs with the name `admin_user[email]` +``` + +If you want to customize the form namespace, you can override the `key` method in your form. + +```ruby +class UserForm < Superform::Rails::Form + def template + render field(:email).input + end + + def key + "user" + end +end + +render UserForm.new(User.new) +# This will render inputs with the name `user[email]` + +render UserForm.new(Admin::User.new) +# This will also render inputs with the name `user[email]` +```` + ## Form field guide Superform tries to strike a balance between "being as close to HTML forms as possible" and not requiring a lot of boilerplate to create forms. This example is contrived, but it shows all the different ways you can render a form. @@ -165,6 +203,7 @@ class SignupForm < ApplicationForm end ``` + ## 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: diff --git a/lib/superform/rails.rb b/lib/superform/rails.rb index eb26420..b93ede9 100644 --- a/lib/superform/rails.rb +++ b/lib/superform/rails.rb @@ -20,7 +20,6 @@ class Form < Component :field, :collection, :namespace, - :key, :assign, :serialize, to: :@namespace @@ -80,7 +79,7 @@ def initialize(model, action: nil, method: nil, **attributes) @action = action @method = method @attributes = attributes - @namespace = Namespace.root(model.model_name.param_key, object: model, field_class: self.class::Field) + @namespace = Namespace.root(key, object: model, field_class: self.class::Field) end def around_template(&) @@ -107,6 +106,10 @@ def submit(value = submit_value, **attributes) ) end + def key + @model.model_name.param_key + end + protected def authenticity_token_field input(