error_helpers.ex 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. defmodule OpenpodWeb.ErrorHelpers do
  2. @moduledoc """
  3. Conveniences for translating and building error messages.
  4. """
  5. use Phoenix.HTML
  6. @doc """
  7. Generates tag for inlined form input errors.
  8. """
  9. def error_tag(form, field) do
  10. Enum.map(Keyword.get_values(form.errors, field), fn error ->
  11. content_tag(:span, translate_error(error),
  12. class: "invalid-feedback",
  13. phx_feedback_for: input_id(form, field)
  14. )
  15. end)
  16. end
  17. @doc """
  18. Translates an error message using gettext.
  19. """
  20. def translate_error({msg, opts}) do
  21. # When using gettext, we typically pass the strings we want
  22. # to translate as a static argument:
  23. #
  24. # # Translate "is invalid" in the "errors" domain
  25. # dgettext("errors", "is invalid")
  26. #
  27. # # Translate the number of files with plural rules
  28. # dngettext("errors", "1 file", "%{count} files", count)
  29. #
  30. # Because the error messages we show in our forms and APIs
  31. # are defined inside Ecto, we need to translate them dynamically.
  32. # This requires us to call the Gettext module passing our gettext
  33. # backend as first argument.
  34. #
  35. # Note we use the "errors" domain, which means translations
  36. # should be written to the errors.po file. The :count option is
  37. # set by Ecto and indicates we should also apply plural rules.
  38. if count = opts[:count] do
  39. Gettext.dngettext(OpenpodWeb.Gettext, "errors", msg, msg, count, opts)
  40. else
  41. Gettext.dgettext(OpenpodWeb.Gettext, "errors", msg, opts)
  42. end
  43. end
  44. end