Skip to content

Instantly share code, notes, and snippets.

@joshchernoff
Last active April 30, 2021 01:55
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshchernoff/f11b3b8126c917752d88d63fc728c2bb to your computer and use it in GitHub Desktop.
Save joshchernoff/f11b3b8126c917752d88d63fc728c2bb to your computer and use it in GitHub Desktop.
defmodule MyAppWeb.InputHelper do
use Phoenix.HTML
def input(form, field, opts \\ []) do
type = Phoenix.HTML.Form.input_type(form, field)
wrapper_classes = Keyword.get_values(opts, :wrapper_class) ++ ["row", "form-group"]
inputs_classes = Keyword.get_values(opts, :input_class) ++ ["form-control"]
if form.errors[field], do: inputs_classes = inputs_classes ++ ["form-control-danger"]
if form.errors[field], do: wrapper_classes = wrapper_classes ++ ["has-danger"]
wrapper_opts = [class: Enum.join(wrapper_classes, " ")]
input_opts =
[class: Enum.join(inputs_classes, " ")] ++
Keyword.drop(opts, [:wrapper_class, :input_class])
label = Keyword.get(opts, :label) || humanize(field)
if input_validations(form, field) |> Keyword.get(:required) do
label = label <> " *"
input_opts = input_opts ++ [required: "required"]
end
content_tag :div, wrapper_opts do
[
content_tag :span, class: "col-sm-2" do
label(form, field, label, class: "col-form-label float-sm-right")
end,
content_tag :div, class: "col-lg-6 col-md-10" do
input = apply(Phoenix.HTML.Form, type, [form, field, input_opts])
error = MyAppWeb.ErrorHelpers.error_tag(form, field)
[input, error || ""]
end
]
end
end
end
@aselder
Copy link

aselder commented May 9, 2020

This is awesome! Thanks.

Looks like there might be one typo on L10. I believe the class should be form-control-danger not form-control-dange.

@joshchernoff
Copy link
Author

@aselder ah thanks.

@akashvibhute
Copy link

akashvibhute commented Jul 25, 2020

I'm new to elixir so I can't fully understand how I'm supposed to properly fix the errors, but for each of the variables updated in the if statements, I get the following error -
variable "label" is unused (if the variable is not meant to be used, prefix it with an underscore) // same for inputs_classes and wrapper_classes.
So in case of errors, they don't get updated with form-control-danger class.

Edit - using Elixir 1.10.4 on windows 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment