How to add error in changeset from controller - phoenix?

How can i add changeset errors from Controller when i am trying to add error like follow

Ecto.Changeset.add_error(changeset, :old_password, "invalid current password")
render conn, "password_new.html", changeset: %{changeset | action: :insert}

error will updated in changeset.errors,

#Ecto.Changeset<action: nil, changes: %{password1: "44", password2: "44", old_password: "xxxx"}, errors: [], data: #XXXX.Password<>, valid?: true>

what mistake i made here?

Data is immutable in Elixir. This is why Ecto.Changeset.add_error/4 returns a new changeset that you need use further on:

updated_changeset = Ecto.Changeset.add_error(changeset, :old_password, "invalid current password")
render conn, "password_new.html",
       changeset: %{updated_changeset | action: :insert}

Elixir does allow the rebinding of variables so you can also write it like this:

changeset = Ecto.Changeset.add_error(changeset, :old_password, "invalid current password")
render conn, "password_new.html",
       changeset: %{changeset | action: :insert}
1 Like

@wmnnd Thank u so much, that solved the issue,but i am not clear about immutable, can u please explain with the example if possible??

Well. Things beeing immutable, means basically that you can’t change them after creation.

So, whenever you wan’t to transform data, you have to assign the new blob of data or pass it further down the chain using a pipe (|>). If you do not do that, the last result will be “forgotten” immediately as in your first version.

Now elixir does allow to “rebind” names, so by doing var = 1; var = var + 1 it sometimes seems that my above statement isn’t true. But what really happens is, that this compiles to some code similar to this: var1 = 1; var2 = var1 + 1.

3 Likes

@NobbZ thank u so much for the valuable note