1
votes

When I have some validation errors in the changeset I want to be able to say to the end user: "credit card can't be blank", or something more complex such as: "your awesome credit card can't be blank".

In short I want the same feature of that: http://gothamjs.io/documentation/1.0.0/validator#change-attributes

I didn't find on the guides something like that, so I came up with that:

error_helpers.ex

  @doc """
  Generates tag for inlined form input errors.
  """
  def error_tag(form, field) do
    if error = form.errors[field] do
      content_tag :span,  to_string(field) <> " " <> translate_error(error), class: "help-block"
    end
  end

You can see I just added to_string(field)

I guess I can come up with an hacky solution with gettext, to translate the field to reach my goal, but I think it's a big no-no to do that.

Doesn't phoenix provide something similar out of the box ? If not, what's the best way to tackle that ?

1

1 Answers

3
votes

Try using generators to check how Phoenix does that:

mix phoenix.gen.html User users name credit_card

To add errors you need to check two places. First one is model. In changeset function you can add:

validate_length(:credit_card, min: 1, message: "your awesome credit card...")

This will add validation error to :credit_card field with given message when it is empty.

Second one is template: you need to use:

<%= form_for @changeset, @actoin, fn f -> %>
  <%= if @changeset.action do %>
    <div class="alert alert-danger">
      <p>Something wrong</p>
    </div>
  <% end %>

  <div class="form-group">
    <%= label f, :credit_card %>
    <%= text_input f, :credit_card %>
    <%= error_tag f, :credit_card %>
  </div>
<% end %>

The error_tag will make sure that your error appears where it should. If you need to translate the error message you can use gettext inside model.

You probably don't have to touch generated controller.