OSDN Git Service

Regular updates
[twpd/master.git] / rails-forms.md
1 ---
2 title: Form helpers
3 hljs_languages: [haml]
4 category: Rails
5 ---
6
7 ## Form builder
8
9 ```haml
10 - form_for @post do |f|
11 ```
12
13 Field names will be prefixed with `post` (the class name), and values will be derived from this object (eg, `f.text_field :name` from `@post.name`).
14
15 ### Options
16
17 ```haml
18 - form_for @post, |
19   url: { method: 'put', action: 'create' }, |
20   html: { class: 'nifty_form' } |
21   do |f|
22 ```
23
24 ## Fields
25
26 ### Text
27
28 ```rb
29 f.text_field :title
30 f.text_area :body, size: '60x12'
31 ```
32
33 ### Checkbox
34
35 ```rb
36 f.check_box :remember_me
37 f.label :remember_me, "Remember me"
38 ```
39
40 ### Radio
41
42 ```rb
43 f.radio_button :gender, 'male'
44 f.label :gender_male, "Male"
45
46 f.radio_button :gender, 'female'
47 f.label :gender_female, "Female"
48 ```
49
50 ### Label
51
52 ```rb
53 f.label :title
54 f.label :title, "Title"
55 f.label :title, "Title", class: "title"
56 f.label(:post, :terms) { "Accept terms" }
57 ```
58
59 ### Submit button
60
61 ```rb
62 f.submit "Create"
63 ```
64
65 ### Hidden fields
66
67 ```rb
68 f.hidden_field :id
69 ```
70
71 ## Misc
72
73 ### The model
74
75 ```ruby
76 f.object
77 ```
78
79 ### Fields for
80
81 ```haml
82 = form_for @post do |f|
83   = fields_for :author, @post.author do |ff|
84     = ff.text_field :name
85 ```
86
87 ### Select dropdowns
88
89 ```rb
90 f.select :city_id, [['Lisbon',1], ['Madrid',2], ...], 4
91 # (4 = selected)
92
93 options_for_select [['Lisbon',1], ['Madrid',2], ...], 4
94 # Just makes <option> tags
95 ```
96
97 ### Collections
98
99 ```
100 f.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial
101 f.collection_select :city_id, City.all, :id, :name
102 # (field, collection, value_key, label_key)
103 ```
104
105 ### Time select
106
107 ```rb
108 f.time_zone_select :time_zone
109 f.date_select :birthday
110 ```
111 ### I18n
112
113 ```yaml
114 helpers:
115   submit:
116     # helpers.submit.<action>
117     create: "Create a %{model}"
118     update: "Confirm changes to %{model}"
119
120     # helpers.submit.<model>.<action>
121     article:
122       create: "Publish article"
123       update: "Update article"
124
125   # helpers.label.<model>.<field>
126   label:
127     post:
128       body: "Your body text"
129 ```
130
131 ### Outside `f`
132
133 ```rb
134 radio_button("post", "category", "rails")
135 radio_button("post", "category", "java")
136
137 # picks from @post.category
138 # <input type="radio" id="post_category_rails" name="post[category]"
139 #  value="rails" checked="checked" />
140 ```
141
142 ### Reference
143
144 ```rb
145 select(method, choices = nil, options = {}, html_options = {}, &block)
146   choices == [ ['label', id], ... ]
147
148 submit(value=nil, options={})
149 ```
150