I have a form backed by a changeset like mentioned here Form bindings β Phoenix LiveView v0.15.7
Say I want a button <button phx-click="foo">Foo</button>
that will populate email
with some value. Problem is I do not want this button to submit the form. Hence params will not contain the form data and without the form data I cannot create new changeset and update socket with it like the other handlers for save
or validate
def handle_event("foo", params, socket) do
IO.inspect(params) #%{"value" => ""}
{:noreply, socket}
end
Any ideas how I can do this?
You can use a phx-change handler to save the part you need later in your socket assigns, when the user press the foo button you can then use those info in your foo handler.
If you donβt want the button to submit the form, be sure to add type="button"
to replace the default type of "submit"
.
2 Likes
Also just to give an example for the solution derek mentioned above:
Assuming you have validation for your form similar to this
def handle_event("validate", %{"user" => params}, socket) do
changeset =
%User{}
|> Users.change_user(params)
|> Map.put(:action, :insert)
{:noreply, assign(socket, changeset: changeset)}
end
then there should be an up-to-date changeset within the socket assigns. Therefore you can use the changeset assign in your handle_event/3
def handle_event("foo", params, socket) do
new_changeset = socket.assigns.changeset |> some_functions
{:noreply, assign(socket, changeset: new_changeset)}
end
1 Like
Thank guys. I am having a moment right now.