MishkaGervaz.Form.Behaviours.FieldType behaviour (MishkaGervaz v0.0.1-alpha.3)

Copy Markdown View Source

Behaviour for form field type renderers.

A field type is a module that knows how to render an input, sanitize and parse incoming params, validate the resulting value, and supply a default UI configuration. The DSL accepts either a built-in token (:text, :textarea, :select, …) or a module implementing this behaviour.

Example

defmodule MyApp.FieldTypes.Color do
  @behaviour MishkaGervaz.Form.Behaviours.FieldType
  use Phoenix.Component

  @impl true
  def render(assigns, _config) do
    ~H"""
    <input type="color" name={@name} value={@value} />
    """
  end

  @impl true
  def sanitize(value, _config), do: value

  @impl true
  def parse_params(value, _config), do: value

  @impl true
  def validate(value, _config), do: {:ok, value}

  @impl true
  def default_ui, do: %{type: :color}
end

Then use in DSL:

field :background_color, MyApp.FieldTypes.Color

Built-in implementations live under MishkaGervaz.Form.Types.Field.* (e.g. MishkaGervaz.Form.Types.Field.Hidden, MishkaGervaz.Form.Types.Field.Relation) and serve as reference implementations.

See MishkaGervaz.Form.Behaviours.Template, MishkaGervaz.Form.Entities.Field, and the MishkaGervaz.Form.Types.Field directory.

Summary

Types

Phoenix LiveView assigns map passed to render/2.

Field configuration map produced by the DSL.

Result of a Phoenix render.

Callbacks

Return the default UI configuration for this field type.

Parse a raw parameter value into the expected type.

Render the form field input.

Sanitize a raw parameter value for this field type.

Validate a field value.

Types

assigns()

@type assigns() :: map()

Phoenix LiveView assigns map passed to render/2.

config()

@type config() :: map()

Field configuration map produced by the DSL.

rendered()

@type rendered() :: Phoenix.LiveView.Rendered.t()

Result of a Phoenix render.

Callbacks

default_ui()

(optional)
@callback default_ui() :: map()

Return the default UI configuration for this field type.

parse_params(raw_value, config)

(optional)
@callback parse_params(raw_value :: any(), config()) :: any()

Parse a raw parameter value into the expected type.

render(assigns, config)

@callback render(assigns(), config()) :: rendered()

Render the form field input.

Parameters

  • assigns — Phoenix assigns with field data
  • config — field configuration map from the DSL

sanitize(value, config)

(optional)
@callback sanitize(value :: any(), config()) :: any()

Sanitize a raw parameter value for this field type.

Called before validation/submission. Text fields strip HTML tags; textarea / json / nested fields pass through unchanged.

validate(value, config)

(optional)
@callback validate(value :: any(), config()) :: {:ok, any()} | {:error, String.t()}

Validate a field value.

Returns {:ok, value} for valid values or {:error, message} for invalid.