Wojciech

Wojciech

I have trouble with simple data update using forms

"I have recently generated authorization using phx.gen and attempted to add an additional field to the table. Subsequently, I implemented a method to update this new field. Then I updated the registration form and added a new form to the settings page. Currently, all functionalities are working as expected, except for the part that allows updating the name.

When i submit form “name_form” i don’t get any errors, but when i look up the database data doesn’t seem to change, i tried using IO.inspect() (probably) everywhere and everything still seems fine.

Form:

    <div>
      <.simple_form
        for={@name_form}
          id="name_form"
          phx-submit="update_name"
          phx-change="validate_name"
        >
          <.input field={@name_form[:name]} type="text" label="Username" autocomplete="off" required />
          <:actions>
            <.button phx-disable-with="Changing...">Change username</.button>
          </:actions>
        </.simple_form>
      </div>

I have two event handlers, one for validation and the other for updating:

   def handle_event("validate_name", %{"user" => user_params}, socket) do
    name_form =
      socket.assigns.current_user
      |> Accounts.change_user_name(user_params)
      |> Map.put(:action, :validate)
      |> to_form()

    {:noreply, assign(socket, name_form: name_form)}
   end

   def handle_event("update_name", %{"user" => user_params}, socket) do
    user = socket.assigns.current_user

    case Accounts.apply_user_name(user, user_params, [validate_name: true]) do
      {:ok, _changeset} ->
        {:noreply, socket}

      {:error, changeset} ->
        {:noreply, assign(socket, :form, to_form(changeset))}
    end
   end

Accounts module, change_user_name returns an %Ecto.Changeset{} for changing the user name:

  def change_user_name(user, attrs \\ %{}, opts \\ []) do
    User.name_changeset(user, attrs, opts)
  end

  def apply_user_name(user, attrs, opts \\ []) do
    user
    |> User.name_changeset(attrs, opts)
    |> Ecto.Changeset.apply_action(:update)
  end

User module contains validate_name changeset which validates name and checks if name in unique:

  def validate_name(changeset, opts) do
    changeset
    |> validate_required([:name])
    |> validate_length(:name, min: 2, max: 36, message: "username must be between 2 and 36 characters")
    |> validate_format(:name, ~r/^[^\s]*$/, message: "cannot have a space at the end")
    |> maybe_validate_unique_name(opts)
  end

  def name_changeset(user, attrs \\ %{}, opts \\ []) do
    user
    |> cast(attrs, [:name])
    |> validate_name(opts)
    |> case do
      %{changes: %{name: _}} = changeset -> changeset
      %{} = changeset -> add_error(changeset, :name, "did not change")
    end
  end

  defp maybe_validate_unique_name(changeset, opts) do
    if Keyword.get(opts, :validate_name, true) do
      changeset
      |> unsafe_validate_unique(:name, Elixirlore.Repo)
      |> unique_constraint(:name)
    else
      changeset
    end
  end

I’d be very grateful for at least some indication where error may be located, thanks in advance.

Marked As Solved

codeanpeace

codeanpeace

Welcome!

Hmm, I don’t see any calls to Ecto.Repo that would actually interact with the database e.g. Repo.update/2 to persist the changeset.

And to clarify, Ecto.Changeset.apply_action(changeset, :update) attempts to add the :update action to the changeset – it does not attempt to update the database itself.

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement