Combo.Inertia.Errors protocol (combo_inertia v2.0.0)

Copy Markdown View Source

Converts a value to Inertia-compatible validation errors.

This protocol allows you to transform various error structures into the format expected by Inertia for client-side validation. The protocol converts error structures into a flat map where keys represent field paths and values are error messages.

Built-in Implementations

This library includes default implementations for:

  • Ecto.Changeset - Converts changeset errors to Inertia-compatible format
  • Map - Validates and passes through properly formatted error maps

Usage with Ecto.Changeset

# In your controller action
def create(conn, %{"post" => post_params}) do
  case Posts.create(post_params)
    # Handle successful validation
    {:ok, post} ->
      redirect(conn, to: "/posts/#{post}")

    # Convert changeset errors and share them with Inertia
    {:error, changeset} ->
      conn
      |> inertia_put_errors(changeset)
      |> redirect(conn, to: "/posts/new")
  end
end

The inertia_put_errors/2 function is a convenience helper provided by Combo.Inertia.Conn that internally uses Combo.Inertia.Errors.to_errors/1 to serialize the changeset errors and share them with the Inertia page under the errors key.

Custom Error Formatting

You can provide a custom message formatting function as the second argument to to_errors/2:

Combo.Inertia.Errors.to_errors(changeset, fn {msg, opts} ->
  # Custom error message formatting logic
  Gettext.dgettext(MyApp.Gettext, "errors", msg, opts)
end)

Implementing for Custom Types

You can implement this protocol for your own error types:

defimpl Combo.Inertia.Errors, for: MyApp.ValidationError do
  def to_errors(validation_error) do
    # Convert your custom error structure to a map of field paths to error
    # messages
    %{
      "field_name" => validation_error.message,
      "nested.field" => "Another error message"
    }
  end

  def to_errors(validation_error, _msg_fun) do
    # Custom implementation with message function
    to_errors(validation_error)
  end
end

Summary

Types

t()

All the types that implement this protocol.

Types

t()

@type t() :: term()

All the types that implement this protocol.

Functions

to_errors(value)

@spec to_errors(term()) :: map() | no_return()

to_errors(value, msg_fun)

@spec to_errors(term(), msg_fun :: function()) :: map() | no_return()