Hi community!
I’m facing a problem with the PhoenixHTML’s form right now…
Let me give some context:
- We have an embedded schema
Review
that embeds oneTopic
- There’s a “Create Review” form where you can search in an input for this Topic
- A list of suggestions is prompted so you can select the topic
- When a suggestion is clicked, a
phx-click
event calls theReview
changeset and casts the topic (we are not inserting anything into a DB here) - Now in the form we change the view so we can display info about the topic (name, description, etc.)
- The user should be able to delete this topic and search for another one using a button “X”
- When clicking this “X” button an event is triggered and I’m calling then
Ecto.Changeset.delete_change/2
.
Code related:
- This is the HTML Heex code for this input and showing of the topic’s info:
<%= if input_value(f, :topic) do %>
<div class="...">
<div class="...">
<%= inputs_for f, :topic, fn fp -> %>
<p> <%= input_value(fp, :name) %> </p>
<p> <%= input_value(fp, :description) %> </p>
<% end %>
</div>
<div class="...">
<button type="button" phx-click="delete" phx-target={@myself} class="...">X</button>
</div>
</div>
<% else %>
<div>
<%= text_input f, :topic_search, "phx-keyup": "form-search", "phx-target": @myself, class: "...", placeholder: "Search for a topic name" %>
<%= if @filtered_results != [] do %>
<div class="...">
<div class="...">
<%= for result <- @filtered_results do %>
<div class="..." phx-click="pick" phx-value-selected-id={result.id} phx-target={@myself}>
<%= result.name %> - <%= result.description %>
</div>
<% end %>
</div>
</div>
<% end %>
</div>
<% end %>
- And this is how we delete the topic from the changeset:
def handle_event("delete", _params, socket) do
new_changeset = Ecto.Changeset.delete_change(socket.assigns.changeset, :topic)
{:noreply, assign(socket, changeset: new_changeset)}
end
Now the problem:
The topic is deleted from the changeset (as expected!) BUT it’s still in the form’s PARAMS so the input_value
function detects we have the topic and tries to show it (but we want to be able to see the search input again and look for a new one!)
This is how the Form looks like after deleting…
%Phoenix.HTML.Form{
action: "#",
data: %MyApp.Review{
...
topic: nil
},
errors: [],
hidden: [],
id: "review",
impl: Phoenix.HTML.FormData.Ecto.Changeset,
index: nil,
name: "review",
options: [method: "post"],
params: %{
"topic" => %{
name: "Topic 1",
description: "A nice topic!",
id: 1
}
},
source: #Ecto.Changeset<action: nil, changes: %{}, errors: [],
data: #MyApp.Review<>, valid?: true>
}
Does anyone know how to delete the params from the form too? Or if I’m doing something wrong when adding the topic to the review…?
Thanks in advance!!