Skip to content

Instantly share code, notes, and snippets.

@fantypants
Last active August 20, 2020 20:06
Show Gist options
  • Save fantypants/6192ed20b06acc177bf260bffb3d50d3 to your computer and use it in GitHub Desktop.
Save fantypants/6192ed20b06acc177bf260bffb3d50d3 to your computer and use it in GitHub Desktop.
defmodule GenysysWeb.SectionTemplateArrayHelpers do
use Phoenix.HTML
"""
Use like (In template):
<%= map_array_input f, :features, ["title", "body", "color", "icon"] %>
<%= map_array_add_button f, :features, ["title", "body", "color", "icon"] %>
Result %{"0" => %{args..}}
"""
def map_array_input(form, field, args) do
values = Phoenix.HTML.Form.input_value(form, field) || [""]
id = Phoenix.HTML.Form.input_id(form,field)
type = Phoenix.HTML.Form.input_type(form, field)
content_tag :ol, id: container_id(id), class: "input_container", data: [index: Enum.count(values) ] do
values
|> Enum.with_index()
|> Enum.map(fn {value, index} ->
form_elements(form,field, value, index, args)
end)
end
end
def map_array_add_button(form, field, args \\ []) do
id = Phoenix.HTML.Form.input_id(form,field)
key_map = Enum.reduce(args, %{}, fn(key, acc) -> Map.merge(acc, %{"#{key}"=> ""}) end)
content = form_elements(form,field,key_map,"__name__", args)
|> safe_to_string
data = [
prototype: content,
container: container_id(id)
];
link("Add", to: "#",data: data, class: "add-section-template-form-field")
end
defp form_elements(form, field, value, index, args) do
type = Phoenix.HTML.Form.input_type(form, field)
id = Phoenix.HTML.Form.input_id(form,field)
new_id = id <> "_#{index}"
inputs = Enum.map(args, fn(key) ->
[name: new_field_name(form,field, index, "#{key}"),
value: value["#{key}"],
label: "#{key}",
id: new_id,
class: "form-control"]
end)
content_tag :div do
[Enum.map(inputs, fn(input) ->
label = label(form, field, humanize(input[:label]))
error = GenysysWeb.ErrorHelpers.error_tag(form, field) || ""
input = apply(Phoenix.HTML.Form, type, [form, field, input])
[label, error, input]
end)]
end
end
defp container_id(id), do: id <> "_container"
defp new_field_name(form, field, index, key) do
Phoenix.HTML.Form.input_name(form, field) <> "[#{index}]" <> "[#{key}]"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment