Alex Antonov
Alex Antonov

Reputation: 15146

How to prevent errors from being shown in the view when I have validate_required?

I have this code in my new.eex:

<%= if Enum.any?(@changeset.errors) do %>
  <%= rendering_code_is_here %>
<% end %>

The problem that if will always be true, because of my changeset has the code:

def changeset(struct, params) do
  struct
  |> cast(bla-bla)
  |> bla-bla-bla
  |> validate_required([:title])
end

So, in my controller I have:

  def new(conn, _params) do
    changeset = Content.changeset(%Content{})
    render conn, "new.html", changeset: changeset
  end

So, it will be always invalid (title is nil). How can I solve this issue?

Upvotes: 1

Views: 48

Answers (1)

AbM
AbM

Reputation: 7779

As you said, your changeset will always have an error and therefore the rendering_code_is_here will run every time.

What you need to check for is if there are any errors after an action (such as Repo.insert or Repo.update) was performed on the changeset using the action field.

<%= if @changeset.action do %>
  <%= rendering_code_is_here %>
<% end %>

Upvotes: 2

Related Questions