Skip to content

Commit eaab209

Browse files
authored
Merge pull request #22 from dhnaranjo/custom_form_namespace
Enable subclasses overriding namespace root key
2 parents d0884f8 + 8160324 commit eaab209

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,44 @@ Then render it from Erb.
104104

105105
Much better!
106106

107+
### Namespacing forms
108+
109+
By default Superform will namespace a form based on the ActiveModel model name param key.
110+
111+
```ruby
112+
class UserForm < Superform::Rails::Form
113+
def template
114+
render field(:email).input
115+
end
116+
end
117+
118+
render LoginForm.new(User.new)
119+
# This will render inputs with the name `user[email]`
120+
121+
render LoginForm.new(Admin::User.new)
122+
# This will render inputs with the name `admin_user[email]`
123+
```
124+
125+
If you want to customize the form namespace, you can override the `key` method in your form.
126+
127+
```ruby
128+
class UserForm < Superform::Rails::Form
129+
def template
130+
render field(:email).input
131+
end
132+
133+
def key
134+
"user"
135+
end
136+
end
137+
138+
render UserForm.new(User.new)
139+
# This will render inputs with the name `user[email]`
140+
141+
render UserForm.new(Admin::User.new)
142+
# This will also render inputs with the name `user[email]`
143+
````
144+
107145
## Form field guide
108146

109147
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.
@@ -162,6 +200,7 @@ class SignupForm < ApplicationForm
162200
end
163201
```
164202

203+
165204
## Extending Superforms
166205

167206
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:

lib/superform/rails.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ class Form < Component
2020
:field,
2121
:collection,
2222
:namespace,
23-
:key,
2423
:assign,
2524
:serialize,
2625
to: :@namespace
@@ -80,7 +79,7 @@ def initialize(model, action: nil, method: nil, **attributes)
8079
@action = action
8180
@method = method
8281
@attributes = attributes
83-
@namespace = Namespace.root(model.model_name.param_key, object: model, field_class: self.class::Field)
82+
@namespace = Namespace.root(key, object: model, field_class: self.class::Field)
8483
end
8584

8685
def around_template(&)
@@ -107,6 +106,10 @@ def submit(value = submit_value, **attributes)
107106
)
108107
end
109108

109+
def key
110+
@model.model_name.param_key
111+
end
112+
110113
protected
111114
def authenticity_token_field
112115
input(

0 commit comments

Comments
 (0)