Njala
Hi everyone!
I’m currently making a web page were we can create protections. Each protection has a list of targets, which are created when you create a protection. Since the length of targets change based on the protection, I needed to implement an add target button, which dynamically adds a target form to the protection one. All of that works.
The problem comes when I submit the form. The params passed to update or create in my protection_controller are just noted like this, where status is one of the option in the target form:
%{
"status_0" => "false"
"status_1" => "true"
"status_2" => "false"
}
which looks ok, but the thing is, I will only get one “status_0”, which will be overiten by the next target form. The expected params would probably look more like this:
%{
"target_0" => {
"status_0" => "false"
"status_1" => "true"
"status_2" => "false"
}
"target_1" => {
"status_0" => "false"
"status_1" => "true"
"status_2" => "false"
}
}
I’m not sure how to make list or maps to give to params, especially since it’s dynamic.
Here’s the code I have to make it dynamic:
In my html
<div class="form-group">
<%= label f, :target, class: "control-label" %>
<%= prot_array_input_new f, :target, @conn %>
<%= prot_array_add_button_new f, :target, @conn %>
<%= error_tag f, :target %>
</div>
In my view:
def prot_array_input_new(form, field, conn) do
values = Phoenix.HTML.Form.input_value(form, field) || [""]
id = Phoenix.HTML.Form.input_id(form, field)
content_tag :ol,
id: prot_container_id(id),
class: "input_container",
data: [
index: Enum.count(values)
] do
values
|> Enum.with_index()
|> Enum.map(
fn {value, index} ->
new_id = id <> "_#{index}"
input_opts = [
name: prot_new_field_name(form, field),
value: value,
id: new_id,
class: "form-control"
]
prot_form_elements_new(form, field, value, index, conn)
end
)
end
end
defp prot_form_elements_new(form, field, value, index, conn) do
id = Phoenix.HTML.Form.input_id(form, field)
new_id = id <> "_#{index}"
input_opts = [
name: prot_new_field_name(form, field),
value: value,
id: new_id,
class: "form-control"
]
content_tag :li do
[
render(MyAppWeb.ProtectionView, "new_target.html", conn: conn, f: form, new_id: new_id),
link(
"Remove",
to: "#",
data: [ id: new_id ],
title: "Remove",
class: "remove-form-field"
)
]
end
end
def prot_array_add_button(form, field, conn) do
id = Phoenix.HTML.Form.input_id(form, field)
content = prot_form_elements_new(form, field, "", "__name__", conn)
|> safe_to_string
data = [
prototype: content,
container: prot_container_id(id)
];
link("Add", to: "#", data: data, class: "add-form-field")
end
And the bit of JS:
const removeElement = ({target}) => {
let el = document.getElementById(target.dataset.id);
let li = el.parentNode;
li.parentNode.removeChild(li);
}
Array.from(document.querySelectorAll(".remove-form-field"))
.forEach(el => {
el.onclick = (e) => {
removeElement(e);
}
});
Array.from(document.querySelectorAll(".add-form-field"))
.forEach(el => {
el.onclick = ({target: {dataset}}) => {
console.log(dataset.container)
let container = document.getElementById(dataset.container);
let index = container.dataset.index;
let newRow = dataset.prototype;
container.insertAdjacentHTML("beforeend", newRow.replace(/__name__/g, index));
container.dataset.index = parseInt(container.dataset.index) + 1;
Array.from(document.querySelectorAll(".remove-form-field")).forEach(el => {
el.onclick = (e) => {
removeElement(e);
}
})
}
});
I’m still new to Elixir and phoenix, so if I missed something, or if something is not clear, ask and I’ll correct myself or tell you any missing information. Thanks in advance!
Trending in Questions
Other Trending Topics
Latest Phoenix Threads
Latest on Elixir Forum
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 7- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
peerreynders
I haven’t parsed through all your code but by your description I have to ask:
Are you trying to nest
formelements?If so, HTML5 disallows that.
Njala
Thanks for your reply!
If by nested form, you mean a tag inside another, no.
What I mean is a nested list of checkboxes, re-used everytime the client clicks “new target”. So a html.eex page inside another one, basically. And I want each of those html to return me a target_param(list of check_boxes checked for each target) that will be used to save the result in my database
dimitarvp
Name your form fields
target_0[],target_1[]etc. (note the opening and closing square bracket in the names). Then you have to make sure that your JS simply appendstarget_0[],target_1[]etc. to the form dynamically.Example: assuming your JS builds form parameters like so (note the seemingly incorrect order):
Then this will result in this HTTP POST payload:
Which on the server will be read as:
In short, you can construct list form fields. It’s not exactly standard but a lot of frameworks support it (Phoenix / Plug included) and all major browsers allow it as well.
Njala
Thanks for the reply!
I’ve seen that, the target, but could not manage to implement it in my html because I’m using the phoenix label. Do you have an example on how to use it in my case, since I created myself the form elements? I’ll still be trying it on my side though, I’ll let you know if I get something.
Thanks a lot!
Njala
So I found my answer:
I basicly go with what @dimitarvp said, I named my fields with , which ends up looking like this:
You need to put multiple layers of brackets like I did to get a list or a map. For instance, the checkbox returns this to my server:
This is readable on my server side and works when creating or modifying a protection with targets.
ps: if you want a list, and not a map, you can do it by not putting anything in the bracket, like so:
this is going to return a list.
Thanks a lot!
dimitarvp
Apologies, I wasn’t available in the last few hours. Glad you solved it!
For future reference, this functionality is contained in the Plug.Conn.Query module.
iexexperiments:This can be very useful to you if you don’t want to modify and test controller methods by hand. Instead, you just use that module’s functions in the
iexREPL.peerreynders
All of this can be fairly cleanly accomplished with
inputs_for/4(seetarget.html.eex).For demonstration purposes only:
The generated HTML from
indexlooks like this:After clicking “Add” and then “Update” the console shows this:
and the page looks like this: