Drop text in input when changing focus

Greetings! I have a bug in my phoenix app. In my template for changing the email page, I have two fields: new email and current password. Thats a template

<%= form_for @email_changeset, "#",
  [phx_change: :validate_email, phx_submit: :save_email, phx_hook: "SavedForm"], fn f-> %>

  <%= hidden_input f, :action, name: "action", value: "update_email" %>

  <%= label f, :email %>
  <%= email_input f, :email, required: true, phx_debounce: "blur"%>
  <%= error_tag f, :email %>


  <%= label f, :password,  for: "current_password_for_email" %>
  <%= password_input f, :password, required: true, name: "password", id: "current_password_for_email" %>
  <%= error_tag f, :password %>

  <div>
    <%= submit "Save", phx_disable_with: "Saving..." %>
  </div>
<% end %>
<% end %>

And that’s the problem: when I type an invalid email (incorrect for changeset), swap to the password field, enter the current password, and then next I want to correct my new mail - my password inputs drop. Maybe someone see better than me whats the problem is here :face_with_head_bandage:

here is potential incorrect code:

def handle_event("validate_email", %{"user" => email}, socket) do
    cset =
      socket.assigns.user
      |> User.email_changeset(email)
      |> Map.put(:action, :update) # act like shit

    {:noreply, assign(socket, email_changeset: cset)}
  end
  def email_changeset(user, attrs) do
    user
    |> cast(attrs, [:email])
    |> validate_email()
    |> case do
      %{changes: %{email: _}} = changeset -> changeset
      %{} = changeset -> add_error(changeset, :email, "did not change")
    end
  end

and here’s what I get for handle_event:

 %{
   "_csrf_token" => "Cnhzd3k_WggHTXcyX0UADCoTFT8MM0UpI473Iy3Z28NSi3r8AeYeaB7C",
   "_target" => ["password"],
   "action" => "update_email",
   "password" => "qweqweqw",
   "user" => %{"email" => "qweqwewqeq"}
 }}

Thank you in advance!

I think you need to set it explicitly for security reasons as mentioned here: Phoenix.HTML.Form — Phoenix.HTML v3.0.4

So, you need a value: input_value(f, :password) on your form password field

Edit: here’s the form bindings documentation

1 Like