Skip to content

Instantly share code, notes, and snippets.

@zporter
Created March 6, 2017 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zporter/ccc65de90f4c65bb7cf7241a48247fab to your computer and use it in GitHub Desktop.
Save zporter/ccc65de90f4c65bb7cf7241a48247fab to your computer and use it in GitHub Desktop.
Simple Form example for Phoenix
defmodule AppName.FormHelpers do
@doc """
Generates a form input tag
Example:
<%= input f,
:name,
input: [
placeholder: gettext("What should we call you?"),
],
hint: gettext("Your name will only be used on the site and in emails sent by us.") %>
"""
@spec input(Phoenix.HTML.Form.t, atom, Keyword.t) :: []
def input(form, field, opts \\ []) do
type = opts[:using] || Phoenix.HTML.Form.input_type(form, field)
wrapper_opts = [class: "form-group #{state_wrapper_class(form, field)}"]
|> Keyword.merge(opts[:wrapper] || [])
label_opts = [class: "control-label"]
|> Keyword.merge(opts[:label] || [])
input_opts = [class: "form-control"]
|> add_input_validations(form, field)
|> Keyword.merge(opts[:input] || [])
content_tag :div, wrapper_opts do
label = label(form, field, humanize(field), label_opts)
input = input(type, form, field, input_opts)
error = error_tag(form, field) || ""
hint = if opts[:hint] do
content_tag(:p, opts[:hint], class: "help-block")
else
""
end
[label, input, error, hint]
end
end
@spec state_wrapper_class(Phoenix.HTML.Form.t, atom) :: String.t
defp state_wrapper_class(form, field) do
cond do
!form.source.action -> "" # the form has not been submitted
form.errors[field] -> "has-error"
true -> "has-success"
end
end
@spec add_input_validations(Keyword.t, Phoenix.HTML.Form.t, atom) :: Keyword.t
defp add_input_validations(opts, form, field) do
Phoenix.HTML.Form.input_validations(form, field)
|> Keyword.merge(opts)
end
@spec input(atom, Phoenix.HTML.Form.t, atom, Keyword.t) :: []
# Implement clauses below for custom inputs.
# defp input(:datepicker, form, field, input_opts) do
# raise "not yet implemented"
# end
defp input(type, form, field, input_opts) do
apply(Phoenix.HTML.Form, type, [form, field, input_opts])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment