Saving the value of a field when following a link

Hello there! I have the following form:

        <.form let={f} for={@changeset} phx-change="validate" phx-target={@myself} phx-submit="submit">
            <div>
              <%= label f, :username %>
              <%= text_input f, :username, required: true %>
              <%= error_tag f, :username %>
            </div>

            <%= link "Transfer field value", to: Routes.user_test_path(@socket, :new) %>

        </.form>

How can I transfer the value from the username field to the following template by clicking button “Transfer field value” and refer to this value? Thanks in advance!

You could replace your link with a submit and handle the redirect in your handle_event/3 like:

def handle_event("submit", %{"user" => %{"username" => name}}, socket) do
  {
    :noreply,
    redirect(socket, to: Routes.user_test_path(socket, :new, username: name)
  }
end

Thanks for your reply! Сan I use something other than submit for the form? I wanted to use it for another action. Or maybe I can use several actions like sumbit on one form?

Hmm, first idea would be to keep track of the username in your assigns (and update it in the “validate” handler) or fetch it from the changeset via Ecto.Changeset.get_change(changeset, :username) and then use a button with a simple phx-click="redirect" and add a handler for that.

1 Like