/
form.ex
1654 lines (1258 loc) · 49.9 KB
/
form.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Phoenix.HTML.Form do
@moduledoc ~S"""
Helpers related to producing HTML forms.
The functions in this module can be used in three
distinct scenarios:
* with changeset data - when information to populate
the form comes from a changeset
* with limited data - when a form is created without
an underlying data layer. In this scenario, you can
use the connection information (aka Plug.Conn.params)
or pass the form values by hand
* outside of a form - when the functions are used directly,
outside of `form_for`
We will explore all three scenarios below.
## With changeset data
The entry point for defining forms in Phoenix is with
the `form_for/4` function. For this example, we will
use `Ecto.Changeset`, which integrates nicely with Phoenix
forms via the `phoenix_ecto` package.
Imagine you have the following action in your controller:
def new(conn, _params) do
changeset = User.changeset(%User{})
render conn, "new.html", changeset: changeset
end
where `User.changeset/2` is defined as follows:
def changeset(user, params \\ %{}) do
cast(user, params, [:name, :age])
end
Now a `@changeset` assign is available in views which we
can pass to the form:
<%= form_for @changeset, Routes.user_path(@conn, :create), fn f -> %>
<label>
Name: <%= text_input f, :name %>
</label>
<label>
Age: <%= select f, :age, 18..100 %>
</label>
<%= submit "Submit" %>
<% end %>
`form_for/4` receives the `Ecto.Changeset` and converts it
to a form, which is passed to the function as the argument
`f`. All the remaining functions in this module receive
the form and automatically generate the input fields, often
by extracting information from the given changeset. For example,
if the user had a default value for age set, it will
automatically show up as selected in the form.
### A note on `:errors`
If no action has been applied to the changeset or action was set to `:ignore`,
no errors are shown on the form object even if the changeset has a non-empty
`:errors` value.
This is useful for things like validation hints on form fields, e.g. an empty
changeset for a new form. That changeset isn't valid, but we don't want to
show errors until an actual user action has been performed.
Ecto automatically applies the action for you when you call
Repo.insert/update/delete, but if you want to show errors manually you can
also set the action yourself, either directly on the `Ecto.Changeset` struct
field or by using `Ecto.Changeset.apply_action/2`.
## With limited data
`form_for/4` expects as first argument any data structure that
implements the `Phoenix.HTML.FormData` protocol. By default,
Phoenix implements this protocol for `Plug.Conn` and `Atom`.
This is useful when you are creating forms that are not backed
by any kind of data layer. Let's assume that we're submitting a
form to the `:new` action in the `FooController`:
<%= form_for @conn, Routes.foo_path(@conn, :new), [as: :foo], fn f -> %>
<%= text_input f, :for %>
<%= submit "Search" %>
<% end %>
`form_for/4` uses the `Plug.Conn` to set input values from the
request parameters.
Alternatively, if you don't have a connection, you can pass `:foo`
as the form data source and explicitly pass the value for every input:
<%= form_for :foo, Routes.foo_path(MyApp.Endpoint, :new), fn f -> %>
<%= text_input f, :for, value: "current value" %>
<%= submit "Search" %>
<% end %>
## Without form data
Sometimes we may want to generate a `text_input/3` or any other
tag outside of a form. The functions in this module also support
such usage by simply passing an atom as first argument instead
of the form.
<%= text_input :user, :name, value: "This is a prepopulated value" %>
## Nested inputs
If your data layer supports embedding or nested associations,
you can use `inputs_for` to attach nested data to the form.
Imagine the following Ecto schemas:
defmodule User do
use Ecto.Schema
schema "users" do
field :name
embeds_one :permalink, Permalink
end
end
defmodule Permalink do
use Ecto.Schema
embedded_schema do
field :url
end
end
In the form, you now can:
<%= form_for @changeset, Routes.user_path(@conn, :create), fn f -> %>
<%= text_input f, :name %>
<%= inputs_for f, :permalink, fn fp -> %>
<%= text_input fp, :url %>
<% end %>
<% end %>
The default option can be given to populate the fields if none
is given:
<%= inputs_for f, :permalink, [default: %Permalink{title: "default"}], fn fp -> %>
<%= text_input fp, :url %>
<% end %>
`inputs_for/4` can be used to work with single entities or
collections. When working with collections, `:prepend` and
`:append` can be used to add entries to the collection
stored in the changeset.
## CSRF protection
The form generates a CSRF token by default. Your application should
check this token on the server to avoid attackers from making requests
on your server in behalf of other users. Phoenix by default checks
this token.
When posting a form with a host in its address, such as "//host.com/path"
instead of only "/path", Phoenix will include the host signature in the
token and validate the token only if the accessed host is the same as
the host in the token. This is to avoid tokens from leaking to third
party applications. If this behaviour is problematic, you can generate
a non-host specific token with `Plug.CSRFProtection.get_csrf_token/0` and
pass it to the form generator via the `:csrf_token` option.
## Phoenix.LiveView integration
Because `Phoenix.LiveView` is unable to compute diffs inside
anonymous functions, Phoenix.HTML provides `form_for/3` that works
without passing an anonymous function. Inside live views, instead of
<%= form_for @changeset, url, opts, fn f -> %>
<%= text_input f, :name %>
<% end %>
you would write
<%= f = form_for @changeset, url, opts %>
<%= text_input f, :name %>
</form>
In the second case, the `form_for` emits only the opening of the
`<form>` tag, which then needs to be closed explicitly in HTML.
Since the anonymous function has been removed, `Phoenix.LiveView`
is able to optimize forms too. Although outside of live views,
we recommend using the first construct.
"""
alias Phoenix.HTML.Form
import Phoenix.HTML
import Phoenix.HTML.Tag
@doc """
Defines the Phoenix.HTML.Form struct.
Its fields are:
* `:source` - the data structure given to `form_for/4` that
implements the form data protocol
* `:impl` - the module with the form data protocol implementation.
This is used to avoid multiple protocol dispatches.
* `:id` - the id to be used when generating input fields
* `:name` - the name to be used when generating input fields
* `:data` - the field used to store lookup data
* `:params` - the parameters associated to this form in case
they were sent as part of a previous request
* `:hidden` - a keyword list of fields that are required for
submitting the form behind the scenes as hidden inputs
* `:options` - a copy of the options given when creating the
form via `form_for/4` without any form data specific key
* `:action` - the action the form is meant to submit to
* `:errors` - a keyword list of errors that associated with
the form
"""
defstruct source: nil,
impl: nil,
id: nil,
name: nil,
data: nil,
hidden: [],
params: %{},
errors: [],
options: [],
index: nil,
action: nil
@type t :: %Form{
source: Phoenix.HTML.FormData.t(),
name: String.t(),
data: %{field => term},
params: %{binary => term},
hidden: Keyword.t(),
options: Keyword.t(),
errors: Keyword.t(),
impl: module,
id: String.t(),
index: nil | non_neg_integer,
action: nil | String.t
}
@type field :: atom | String.t()
defimpl Phoenix.HTML.Safe do
def to_iodata(%{action: action, options: options}) do
{:safe, contents} = form_tag(action, options)
contents
end
end
@doc """
Converts an attribute/form field into its humanize version.
iex> humanize(:username)
"Username"
iex> humanize(:created_at)
"Created at"
iex> humanize("user_id")
"User"
"""
def humanize(atom) when is_atom(atom), do: humanize(Atom.to_string(atom))
def humanize(bin) when is_binary(bin) do
bin =
if String.ends_with?(bin, "_id") do
binary_part(bin, 0, byte_size(bin) - 3)
else
bin
end
bin |> String.replace("_", " ") |> String.capitalize()
end
@doc """
Generates a form tag with a form builder **without** options or an anonymous function.
<%= f = form_for @changeset, Routes.user_path(@conn, :create) %>
Name: <%= text_input f, :name %>
</form>
A shortcut for `form_for(changeset, url, [])`.
"""
@spec form_for(Phoenix.HTML.FormData.t(), String.t()) :: Phoenix.HTML.Form.t()
def form_for(form_data, action) do
form_for(form_data, action, [])
end
@doc """
Generates a form tag with a form builder **without** an anonymous function.
This functionality exists mostly for integration with `Phoenix.LiveView`
that replaces the anonymous function for explicit closing of the `<form>`
tag:
<%= f = form_for @changeset, Routes.user_path(@conn, :create), opts %>
Name: <%= text_input f, :name %>
</form>
See the [Phoenix.LiveView integration](#module-phoenix-liveview-integration)
section in module documentation for examples of using this function.
See `form_for/4` for the available options.
"""
@spec form_for(Phoenix.HTML.FormData.t(), String.t(), Keyword.t()) ::
Phoenix.HTML.Form.t()
def form_for(form_data, action, options) when is_list(options) do
%{Phoenix.HTML.FormData.to_form(form_data, options) | action: action}
end
@doc """
Generates a form tag with a form builder and an anonymous function.
<%= form_for @changeset, Routes.user_path(@conn, :create), fn f -> %>
Name: <%= text_input f, :name %>
<% end %>
See the module documentation for examples of using this function.
## Options
* `:as` - the server side parameter in which all params for this
form will be collected (i.e. `as: :user_params` would mean all fields
for this form will be accessed as `conn.params.user_params` server
side). Automatically inflected when a changeset is given.
* `:method` - the HTTP method. If the method is not "get" nor "post",
an input tag with name `_method` is generated along-side the form tag.
Defaults to "post".
* `:multipart` - when true, sets enctype to "multipart/form-data".
Required when uploading files
* `:csrf_token` - for "post" requests, the form tag will automatically
include an input tag with name `_csrf_token`. When set to false, this
is disabled
* `:errors` - use this to manually pass a keyword list of errors to the form
(for example from `conn.assigns[:errors]`). This option is only used when a
connection is used as the form source and it will make the errors available
under `f.errors`.
* Other options will be passed as html attributes.
ie, `class: "foo", id: "bar"`
See `Phoenix.HTML.Tag.form_tag/2` for more information on the
options above.
"""
@spec form_for(Phoenix.HTML.FormData.t(), String.t(), (t -> Phoenix.HTML.unsafe())) ::
Phoenix.HTML.safe()
@spec form_for(Phoenix.HTML.FormData.t(), String.t(), Keyword.t(), (t -> Phoenix.HTML.unsafe())) ::
Phoenix.HTML.safe()
def form_for(form_data, action, options \\ [], fun) when is_function(fun, 1) do
%{action: action, options: options} = form = form_for(form_data, action, options)
html_escape([form_tag(action, options), fun.(form), raw("</form>")])
end
@doc """
Generate a new form builder for the given parameter in form.
See the module documentation for examples of using this function.
## Options
* `:id` - the id to be used in the form, defaults to the
concatenation of the given `field` to the parent form id
* `:as` - the name to be used in the form, defaults to the
concatenation of the given `field` to the parent form name
* `:default` - the value to use if none is available
* `:prepend` - the values to prepend when rendering. This only
applies if the field value is a list and no parameters were
sent through the form.
* `:append` - the values to append when rendering. This only
applies if the field value is a list and no parameters were
sent through the form.
* `:skip_hidden` - skip the automatic rendering of hidden
fields to allow for more tight control over the generated
markup. You can access `form.hidden` to generate them manually
within the supplied callback.
"""
@spec inputs_for(t, field, Keyword.t(), (t -> Phoenix.HTML.unsafe())) :: Phoenix.HTML.safe()
def inputs_for(%{impl: impl} = form, field, options \\ [], fun)
when is_atom(field) or is_binary(field) do
{skip, options} = Keyword.pop(options, :skip_hidden, false)
options =
form.options
|> Keyword.take([:multipart])
|> Keyword.merge(options)
forms = impl.to_form(form.source, form, field, options)
html_escape(
Enum.map(forms, fn form ->
if skip do
fun.(form)
else
hidden = Enum.map(form.hidden, fn {k, v} -> hidden_input(form, k, value: v) end)
[hidden, fun.(form)]
end
end)
)
end
@doc """
Returns a value of a corresponding form field.
The `form` should either be a `Phoenix.HTML.Form` emitted
by `form_for` or an atom.
When a form is given, it will lookup for changes and then
fallback to parameters and finally fallback to the default
struct/map value.
"""
@spec input_value(t | atom, field) :: term
def input_value(%{source: source, impl: impl} = form, field)
when is_atom(field) or is_binary(field) do
try do
impl.input_value(source, form, field)
rescue
UndefinedFunctionError ->
case Map.fetch(form.params, field_to_string(field)) do
{:ok, value} ->
value
:error ->
Map.get(form.data, field)
end
end
end
def input_value(name, _field) when is_atom(name), do: nil
@doc """
Returns an id of a corresponding form field.
The form should either be a `Phoenix.HTML.Form` emitted
by `form_for` or an atom.
"""
@spec input_id(t | atom, field) :: String.t()
def input_id(%{id: nil}, field), do: "#{field}"
def input_id(%{id: id}, field) when is_atom(field) or is_binary(field) do
"#{id}_#{field}"
end
def input_id(name, field) when (is_atom(name) and is_atom(field)) or is_binary(field) do
"#{name}_#{field}"
end
@doc """
Returns an id of a corresponding form field and value attached to it.
Useful for radio buttons and inputs like multiselect checkboxes.
"""
@spec input_id(t | atom, field, Phoenix.HTML.Safe.t()) :: String.t()
def input_id(name, field, value) do
{:safe, value} = html_escape(value)
value_id = value |> IO.iodata_to_binary() |> String.replace(~r/\W/u, "_")
input_id(name, field) <> "_" <> value_id
end
@doc """
Returns a name of a corresponding form field.
The first argument should either be a `Phoenix.HTML.Form` emitted
by `form_for` or an atom.
## Examples
iex> Phoenix.HTML.Form.input_name(:user, :first_name)
"user[first_name]"
"""
@spec input_name(t | atom, field) :: String.t()
def input_name(form_or_name, field)
def input_name(%{name: nil}, field), do: to_string(field)
def input_name(%{name: name}, field) when is_atom(field) or is_binary(field),
do: "#{name}[#{field}]"
def input_name(name, field) when (is_atom(name) and is_atom(field)) or is_binary(field),
do: "#{name}[#{field}]"
@doc """
Returns the HTML5 validations that would apply to
the given field.
"""
@spec input_validations(t, field) :: Keyword.t()
def input_validations(%{source: source, impl: impl} = form, field)
when is_atom(field) or is_binary(field) do
# TODO: Remove me on 3.0
try do
impl.input_validations(source, form, field)
rescue
UndefinedFunctionError -> impl.input_validations(source, field)
end
end
@mapping %{
"url" => :url_input,
"email" => :email_input,
"search" => :search_input,
"password" => :password_input
}
@doc """
Gets the input type for a given field.
If the underlying input type is a `:text_field`,
a mapping could be given to further inflect
the input type based solely on the field name.
The default mapping is:
%{"url" => :url_input,
"email" => :email_input,
"search" => :search_input,
"password" => :password_input}
"""
@spec input_type(t, field) :: atom
def input_type(%{impl: impl, source: source} = form, field, mapping \\ @mapping)
when is_atom(field) or is_binary(field) do
# TODO: Remove me on 3.0
type =
try do
impl.input_type(source, form, field)
rescue
UndefinedFunctionError -> impl.input_type(source, field)
end
if type == :text_input do
field = field_to_string(field)
Enum.find_value(mapping, type, fn {k, v} ->
String.contains?(field, k) && v
end)
else
type
end
end
## Form helpers
@doc """
Generates a text input.
The form should either be a `Phoenix.HTML.Form` emitted
by `form_for` or an atom.
All given options are forwarded to the underlying input,
default values are provided for id, name and value if
possible.
## Examples
# Assuming form contains a User schema
text_input(form, :name)
#=> <input id="user_name" name="user[name]" type="text" value="">
text_input(:user, :name)
#=> <input id="user_name" name="user[name]" type="text" value="">
"""
def text_input(form, field, opts \\ []) do
generic_input(:text, form, field, opts)
end
@doc """
Generates a hidden input.
See `text_input/3` for example and docs.
"""
def hidden_input(form, field, opts \\ []) do
generic_input(:hidden, form, field, opts)
end
@doc """
Generates an email input.
See `text_input/3` for example and docs.
"""
def email_input(form, field, opts \\ []) do
generic_input(:email, form, field, opts)
end
@doc """
Generates a number input.
See `text_input/3` for example and docs.
"""
def number_input(form, field, opts \\ []) do
generic_input(:number, form, field, opts)
end
@doc """
Generates a password input.
For security reasons, the form data and parameter values
are never re-used in `password_input/3`. Pass the value
explicitly if you would like to set one.
See `text_input/3` for example and docs.
"""
def password_input(form, field, opts \\ []) do
opts =
opts
|> Keyword.put_new(:type, "password")
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
tag(:input, opts)
end
@doc """
Generates an url input.
See `text_input/3` for example and docs.
"""
def url_input(form, field, opts \\ []) do
generic_input(:url, form, field, opts)
end
@doc """
Generates a search input.
See `text_input/3` for example and docs.
"""
def search_input(form, field, opts \\ []) do
generic_input(:search, form, field, opts)
end
@doc """
Generates a telephone input.
See `text_input/3` for example and docs.
"""
def telephone_input(form, field, opts \\ []) do
generic_input(:tel, form, field, opts)
end
@doc """
Generates a color input.
Warning: this feature isn't available in all browsers.
Check `http://caniuse.com/#feat=input-color` for further informations.
See `text_input/3` for example and docs.
"""
def color_input(form, field, opts \\ []) do
generic_input(:color, form, field, opts)
end
@doc """
Generates a range input.
See `text_input/3` for example and docs.
"""
def range_input(form, field, opts \\ []) do
generic_input(:range, form, field, opts)
end
@doc """
Generates a date input.
Warning: this feature isn't available in all browsers.
Check `http://caniuse.com/#feat=input-datetime` for further informations.
See `text_input/3` for example and docs.
"""
def date_input(form, field, opts \\ []) do
generic_input(:date, form, field, opts)
end
@doc """
Generates a datetime-local input.
Warning: this feature isn't available in all browsers.
Check `http://caniuse.com/#feat=input-datetime` for further informations.
See `text_input/3` for example and docs.
"""
def datetime_local_input(form, field, opts \\ []) do
value = Keyword.get(opts, :value, input_value(form, field))
opts = Keyword.put(opts, :value, datetime_local_input_value(value))
generic_input(:"datetime-local", form, field, opts)
end
defp datetime_local_input_value(%NaiveDateTime{} = value) do
<<date::10-binary, ?\s, hour_minute::5-binary, _rest::binary>> =
NaiveDateTime.to_string(value)
[date, ?T, hour_minute]
end
defp datetime_local_input_value(other), do: other
@doc """
Generates a time input.
Warning: this feature isn't available in all browsers.
Check `http://caniuse.com/#feat=input-datetime` for further informations.
## Options
* `:precision` - Allowed values: `:minute`, `:second`, `:millisecond`.
Defaults to `:minute`.
All other options are forwarded. See `text_input/3` for example and docs.
## Examples
time_input form, :time
#=> <input id="form_time" name="form[time]" type="time" value="23:00">
time_input form, :time, precision: :second
#=> <input id="form_time" name="form[time]" type="time" value="23:00:00">
time_input form, :time, precision: :millisecond
#=> <input id="form_time" name="form[time]" type="time" value="23:00:00.000">
"""
def time_input(form, field, opts \\ []) do
{precision, opts} = Keyword.pop(opts, :precision, :minute)
value = opts[:value] || input_value(form, field)
opts = Keyword.put(opts, :value, truncate_time(value, precision))
generic_input(:time, form, field, opts)
end
defp truncate_time(%Time{} = time, :minute) do
time
|> Time.to_string()
|> String.slice(0, 5)
end
defp truncate_time(%Time{} = time, precision) do
time
|> Time.truncate(precision)
|> Time.to_string()
end
defp truncate_time(value, _), do: value
defp generic_input(type, form, field, opts)
when is_list(opts) and (is_atom(field) or is_binary(field)) do
opts =
opts
|> Keyword.put_new(:type, type)
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
|> Keyword.put_new(:value, input_value(form, field))
|> Keyword.update!(:value, &maybe_html_escape/1)
tag(:input, opts)
end
defp maybe_html_escape(nil), do: nil
defp maybe_html_escape(value), do: html_escape(value)
@doc """
Generates a textarea input.
All given options are forwarded to the underlying input,
default values are provided for id, name and textarea
content if possible.
## Examples
# Assuming form contains a User schema
textarea(form, :description)
#=> <textarea id="user_description" name="user[description]"></textarea>
## New lines
Notice the generated textarea includes a new line after
the opening tag. This is because the HTML spec says new
lines after tags must be ignored and all major browser
implementations do that.
So in order to avoid new lines provided by the user
from being ignored when the form is resubmitted, we
automatically add a new line before the text area
value.
"""
def textarea(form, field, opts \\ []) do
opts =
opts
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
{value, opts} = Keyword.pop(opts, :value, input_value(form, field))
content_tag(:textarea, ["\n", html_escape(value || "")], opts)
end
@doc """
Generates a file input.
It requires the given form to be configured with `multipart: true`
when invoking `form_for/4`, otherwise it fails with `ArgumentError`.
See `text_input/3` for example and docs.
"""
def file_input(form, field, opts \\ []) do
if match?(%Form{}, form) and !form.options[:multipart] do
raise ArgumentError,
"file_input/3 requires the enclosing form_for/4 " <>
"to be configured with multipart: true"
end
opts =
opts
|> Keyword.put_new(:type, :file)
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
opts =
if opts[:multiple] do
Keyword.update!(opts, :name, &"#{&1}[]")
else
opts
end
tag(:input, opts)
end
@doc """
Generates a submit button to send the form.
All options are forwarded to the underlying button tag.
## Examples
submit "Submit"
#=> <button type="submit">Submit</button>
"""
def submit([do: _] = block_option), do: submit([], block_option)
def submit(_, opts \\ [])
def submit(opts, [do: _] = block_option) do
opts = Keyword.put_new(opts, :type, "submit")
content_tag(:button, opts, block_option)
end
def submit(value, opts) do
opts = Keyword.put_new(opts, :type, "submit")
content_tag(:button, value, opts)
end
@doc """
Generates a reset input to reset all the form fields to
their original state.
All options are forwarded to the underlying input tag.
## Examples
reset "Reset"
#=> <input type="reset" value="Reset">
reset "Reset", class: "btn"
#=> <input type="reset" value="Reset" class="btn">
"""
def reset(value, opts \\ []) do
opts =
opts
|> Keyword.put_new(:type, "reset")
|> Keyword.put_new(:value, value)
tag(:input, opts)
end
@doc """
Generates a radio button.
Invoke this function for each possible value you want
to be sent to the server.
## Examples
# Assuming form contains a User schema
radio_button(form, :role, "admin")
#=> <input id="user_role_admin" name="user[role]" type="radio" value="admin">
## Options
All options are simply forwarded to the underlying HTML tag.
"""
def radio_button(form, field, value, opts \\ []) do
escaped_value = html_escape(value)
opts =
opts
|> Keyword.put_new(:type, "radio")
|> Keyword.put_new(:id, input_id(form, field, escaped_value))
|> Keyword.put_new(:name, input_name(form, field))
opts =
if escaped_value == html_escape(input_value(form, field)) do
Keyword.put_new(opts, :checked, true)
else
opts
end
tag(:input, [value: escaped_value] ++ opts)
end
@doc """
Generates a checkbox.
This function is useful for sending boolean values to the server.
## Examples
# Assuming form contains a User schema
checkbox(form, :famous)
#=> <input name="user[famous]" type="hidden" value="false">
<input checked="checked" id="user_famous" name="user[famous]" type="checkbox" value="true">
## Options
* `:checked_value` - the value to be sent when the checkbox is checked.
Defaults to "true"
* `:hidden_input` - controls if this function will generate a hidden input
to submit the unchecked value or not. Defaults to "true"
* `:unchecked_value` - the value to be sent when the checkbox is unchecked,
Defaults to "false"
* `:value` - the value used to check if a checkbox is checked or unchecked.
The default value is extracted from the form data if available
All other options are forwarded to the underlying HTML tag.
## Hidden fields
Because an unchecked checkbox is not sent to the server, Phoenix
automatically generates a hidden field with the unchecked_value
*before* the checkbox field to ensure the `unchecked_value` is sent
when the checkbox is not marked. Set `hidden_input` to false If you
don't want to send values from unchecked checkbox to the server.
"""
def checkbox(form, field, opts \\ []) do
opts =
opts
|> Keyword.put_new(:type, "checkbox")
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
{value, opts} = Keyword.pop(opts, :value, input_value(form, field))
{checked_value, opts} = Keyword.pop(opts, :checked_value, true)
{unchecked_value, opts} = Keyword.pop(opts, :unchecked_value, false)
{hidden_input, opts} = Keyword.pop(opts, :hidden_input, true)
# We html escape all values to be sure we are comparing
# apples to apples. After all we may have true in the data
# but "true" in the params and both need to match.
value = html_escape(value)
checked_value = html_escape(checked_value)
unchecked_value = html_escape(unchecked_value)
opts =
if value == checked_value do
Keyword.put_new(opts, :checked, true)
else
opts
end
if hidden_input do
html_escape([
tag(:input, name: Keyword.get(opts, :name), type: "hidden", value: unchecked_value),