View Source Surface.Components.Form.ErrorTag (Surface Form v0.2.0)

A component inspired by error_tag/3 that ships with mix phx.new in MyAppWeb.ErrorHelpers.

Renders error messages if any exist regarding the given field.

Error Translation

Changeset errors are translated using the default error translator that ships with phoenix when generated with mix phx.new --no-gettext.

When using Gettext, you can use configuration to route all errors through the MyAppWeb.ErrorHelpers.translate_error/1 function generated by Phoenix, which utilizes Gettext. You need to provide a tuple with the module and the name of the function (as an atom) as follows:

config :surface, :components, [
  {Surface.Components.Form.ErrorTag, default_translator: {MyAppWeb.ErrorHelpers, :translate_error}}
]

Note: If you don't configure a default_translator, Surface will try to translate errors using a built-in message translator which may not cover all types of errors. If the error cannot be translated, a generic "invalid value" will be returned and a warning will be emitted, reminding the user to set up a proper default_translator that can handle such cases.

There is also a translator prop which can be used on a case-by-case basis. It overrides the configuration.

Examples

<ErrorTag field="password" />
<Field name="password">
  <ErrorTag />
</Field>
<ErrorTag feedback_for="confirm_password_for_reset" />
<ErrorTag class="custom-css-classes" />
<ErrorTag translator={&CustomTranslationLib.translate_error/1} />

Properties

  • form :form, from_context: {Surface.Components.Form, :form} - An identifier for the form
  • field :any, from_context: {Surface.Components.Form.Field, :field} - An identifier for the associated field
  • class :css_class - Classes to apply to each error tag <span>.

This can also be set via config, for example:

config :surface, :components, [
  {Surface.Components.Form.ErrorTag, default_class: "invalid-feedback"}
]

However, the prop overrides the config value if provided.

  • translator :fun - A function that takes one argument {msg, opts} and returns the translated error message as a string. If not provided, falls back to Phoenix's default implementation.

This can also be set via config, for example:

config :surface, :components, [
  {Surface.Components.Form.ErrorTag, default_translator: {MyApp.Gettext, :translate_error}}
]
  • feedback_for :string - If you changed the default ID on the input, provide it here. (Useful when there are multiple forms on the same page, each with an input of the same name. LiveView will exhibit buggy behavior without assigning separate id's to each.)

Summary

Functions

Callback implementation for Surface.Component.render/1.

Translates an error message.

Functions

Callback implementation for Surface.Component.render/1.

Translates an error message.

This is the fallback (Phoenix's default implementation) if a translator is not provided via config or the translate prop.