PhoenixMTM v1.0.0 PhoenixMTM.Helpers View Source
Provides HTML helpers for Phoenix.
Link to this section Summary
Functions
Generates a list of checkboxes and labels to update a Phoenix many_to_many relationship
Link to this section Functions
Link to this function
collection_checkboxes(form, field, collection, opts \\ []) View Source
Generates a list of checkboxes and labels to update a Phoenix many_to_many relationship.
Basic Example
<%= PhoenixMTM.Helpers.collection_checkboxes f, :tags,
Enum.map(@tags, &({&1.name, &1.id})),
selected: Enum.map(f.data.tags, &(&1.id)) %>
Custom <input>
and <label>
options
<%= PhoenixMTM.Helpers.collection_checkboxes f, :tags,
Enum.map(@tags, &({&1.name, &1.id})),
selected: Enum.map(f.data.tags, &(&1.id)),
label_opts: [class: "form-input"], input_opts: [class: "form-control"] %>
Options
:selected
- a list of options that should be pre-selected:input_opts
- a list of attributes to be applied to each checkbox input:label_opts
- a list of attributes to be applied to each checkbox label:wrapper
- a function to wrap the HTML structure of each checkbox/label:mapper
- a function to customize the HTML structure of each checkbox/label
Wrapper
A wrapper
function can be used to wrap each checkbox and label pair in one
or more HTML elements.
The wrapper function receives the pair as a single argument, and should return
a safe
tuple as expected by Phoenix.
A simplified version of this is to call Phoenix.HTML.Tag.content_tag
<%= PhoenixMTM.Helpers.collection_checkboxes f, :tags,
Enum.map(@tags, &({&1.name, &1.id})),
selected: Enum.map(f.data.tags, &(&1.id)),
wrapper: &Phoenix.HTML.Tag.content_tag(:p, &1)
Mapper
A mapper
function can be used to customize the structure of the checkbox and
label pair.
The mapper function receives the form, field name, input options, label text,
label options, and helper options, and should return a safe
tuple as expected
by Phoenix.
# Somewhere in your application
defmodule CustomMappers do
use PhoenixMTM.Mappers
def bootstrap(form, field, input_opts, label_content, label_opts, _opts) do
content_tag(:div, class: "checkbox") do
label(form, field, label_opts) do
[
tag(:input, input_opts),
html_escape(label_content)
]
end
end
end
end
# In your template
<%= PhoenixMTM.Helpers.collection_checkboxes f, :tags,
Enum.map(@tags, &({&1.name, &1.id})),
selected: Enum.map(f.data.tags, &(&1.id)),
mapper: &CustomMappers.bootstrap/6