Skip to content

Commit f8f48ba

Browse files
authored
Add a basic example
1 parent 67d6f03 commit f8f48ba

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

examples/basic.md

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# Basic form example
2+
3+
## Form
4+
```ruby
5+
class ContactForm < ApplicationForm
6+
proxy_for Contact, :@contact
7+
8+
attribute :first_name
9+
attribute :last_name
10+
attribute :birth_date, :date
11+
12+
validates :first_name, presence: true
13+
validates :last_name, presence: true
14+
validates :birth_date, presence: true
15+
16+
17+
def setup(contact)
18+
@contact = contact
19+
self.first_name = @contact.first_name
20+
self.last_name = @contact.last_name
21+
self.birth_date = @contact.birth_date
22+
## You could also do :
23+
# self.attributes = @contact.attributes.slice(:first_name, :last_name, birth_date)
24+
end
25+
26+
def perform
27+
@contact.update!(
28+
first_name:,
29+
last_name:,
30+
birth_date:
31+
)
32+
end
33+
end
34+
```
35+
36+
## Controller
37+
```ruby
38+
class ContactsController
39+
def new
40+
@form = ContactForm.new(Contact.new)
41+
end
42+
43+
def create
44+
@form = ContactForm.new(Contact.new)
45+
46+
if @form.submit(params[:contact])
47+
redirect_to root_path, notice: "Contact created"
48+
else
49+
render :new, status: :unprocessable_entity
50+
end
51+
end
52+
53+
def edit
54+
@contact = Contact.find(params[:id])
55+
@form = ContactForm.new(@contact)
56+
end
57+
58+
def update
59+
@contact = Contact.find(params[:id])
60+
@form = ContactForm.new(@contact)
61+
62+
if @form.submit(params[:contact])
63+
redirect_to root_path, notice: "Contact updated"
64+
else
65+
render :edit, status: :unprocessable_entity
66+
end
67+
end
68+
end
69+
```
70+
71+
## Views
72+
### new.html.erb and edit.html.erb
73+
```erb
74+
<%= render "form", form: @form %>
75+
```
76+
77+
### _form.html.erb
78+
```erb
79+
<%= form_with(model: form) do |f| %>
80+
<%= f.text_field :first_name, placeholder: "First name" %>
81+
<%= f.text_field :last_name, placeholder: "Last name" %>
82+
<%= f.date_field :birth_date %>
83+
<%= f.submit "Save" %>
84+
<% end %>
85+
```

0 commit comments

Comments
 (0)