Hello!
I’ve been banging my head against a wall… Maybe someone can help.
My question kind of goes deep but hopefully I can boil it down…
I have a really simple form where the user enters a float number. In addition to allowing data entry using a keyboard, I also created a “numeric keypad” made up of buttons, for entering the number more easily on a mobile phone.
How do I program the keys to append text to the input field?
Here’s the code I tried:
# This is my standard handle_event in the form component - nothing unusual
def handle_event("validate", %{"data" => form_params}, socket) do
changeset = Context.to_changeset(socket.assigns.data, form_params)
form = to_form(changeset, action: :validate, as: "data")
{:noreply, assign(socket, form: form)}
end
# This is how I'm handling the button click
def handle_event("append", %{"text" => text}, socket) do
new_weight = get_param(socket.assigns.form, "weight") <> text
new_params = %{"date" => get_param(socket.assigns.form, "date"), "weight" => new_weight}
handle_event("validate", %{"data" => new_params}, socket)
end
This code works: text is appended to the input box.
HOWEVER, validation does not kick in. For example, if I enter “2.0.0” using the buttons, no error is displayed. When I enter the same using the keyboard, the form displays the red “Invalid weight” message.
I’ve been racking my brain but I can’t explain why the error does not appear in the first scenario. I compared the form assign and the changeset in both cases and they are exactly the same, meaning that the changeset is marked as invalid and has the error message.
This is why I suspect that my way of calling handle_event("validate", ...)
from within handle_event("append", ...)
is not the right way of doing that. But I can’t find any examples online.
Am I going to have to use JS hooks or something?
Thanks,
Michal