DynamicForm.Payload (DynamicForm v0.19.0)

Copy Markdown View Source

The value threaded through the form lifecycle.

The component builds a payload from the form's changeset on every change and submit. Lifecycle callbacks (on_change and on_submit) receive the payload and return it — transformed or untouched — and it is delivered to the parent LiveView as {:dynamic_form, event, payload} (or, on a valid submission, to a custom on_success callback when one is defined).

Fields

  • :id - The form component's id, for matching in handle_info/2
  • :changeset - The form's Ecto.Changeset after built-in validations and any callbacks so far. Its valid? flag is the single source of truth for whether the submission is valid.
  • :data - The applied changeset data (Ecto.Changeset.apply_changes/1)
  • :extra - Empty map by default; callbacks can stash derived data here (a normalized phone number, a geocoded address) for the parent's handle_info/2 to use

Marking a payload invalid

Validity lives on the changeset — there is no separate flag to keep in sync. Reject a submission with add_error/4: the error renders inline on the form field, the changeset becomes invalid, and the submission is withheld from the parent:

def on_submit(payload) do
  if phone_number_valid?(payload.data[:phone]) do
    payload
  else
    DynamicForm.Payload.add_error(payload, :phone, "is not a valid phone number")
  end
end

Summary

Functions

Adds an error to the payload's changeset, marking the submission invalid.

Builds a payload from a form component id and its changeset.

Stores a value under key in the payload's extra map.

Whether the payload represents a valid submission.

Types

t()

@type t() :: %DynamicForm.Payload{
  changeset: Ecto.Changeset.t(),
  data: map(),
  extra: map(),
  id: String.t()
}

Functions

add_error(payload, field, message, opts \\ [])

@spec add_error(t(), atom(), String.t(), keyword()) :: t()

Adds an error to the payload's changeset, marking the submission invalid.

The way for on_change/on_submit callbacks to reject a submission: the error renders inline on the form field, and the changeset's valid? flag flips to false (as with any Ecto.Changeset.add_error/4 call).

Accepts the same arguments as Ecto.Changeset.add_error/4.

new(id, changeset)

@spec new(String.t(), Ecto.Changeset.t()) :: t()

Builds a payload from a form component id and its changeset.

data is the applied changeset data.

put_extra(payload, key, value)

@spec put_extra(t(), term(), term()) :: t()

Stores a value under key in the payload's extra map.

Lets on_submit pass derived data forward to the parent's handle_info/2 without a side effect:

payload
|> DynamicForm.Payload.put_extra(:normalized_phone, normalized)

valid?(payload)

@spec valid?(t()) :: boolean()

Whether the payload represents a valid submission.

Reads the changeset's valid? flag — the single source of truth.