coderVishal
coderVishal

Reputation: 9079

Phoenix Phoenix.HTML.Safe not implemented

On my post model, I have implemented a simple validation

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> validate_length(:content, min: 2)
    |> validate_length(:content, max: 500)
  end

On submitting the Post create form the view, I would like to show errors if there was something wrong from user submission, here is the view that renders the error

<%= form_for @changeset, @action, fn f -> %>
  <%= if @changeset.action do %>
    <div class="alert alert-danger">
      <p>Oops, something went wrong! Please check the errors below:</p>
      <ul>
        <%= for {attr, message} <- f.errors do %>
          <%IEx.pry%>
          <li><%= humanize(attr) %> <%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

I am getting this error (Protocol.UndefinedError) protocol Phoenix.HTML.Safe not implemented for {"should be at least %{count} character(s)", [count: 2]} (phoenix_html) lib/phoenix_html/safe.ex:74: Phoenix.HTML.Safe.Tuple.to_iodata/1

I cant find out why this is happening, I had a similar validation in another phoenix app(also in the phoenix docs) that worked perfectly

Update - The earlier app was using using an older Ecto and phoenix version , I am currently on Ecto 2.0 + and Phoenix 1.1,

Upvotes: 3

Views: 3135

Answers (1)

Dogbert
Dogbert

Reputation: 222040

The correct way to show the error message in a Changeset is to use MyApp.ErrorHelpers.translate_error/1.

Replace:

<li><%= humanize(attr) %> <%= message %></li>

with

<li><%= humanize(attr) %> <%= translate_error(message) %></li>

Demo:

iex(1)> MyApp.ErrorHelpers.translate_error {"should be at least %{count} character(s)", [count: 2]}
"should be at least 2 character(s)"

Upvotes: 6

Related Questions