Build an admin form

v0.0.12

The form section of the mishka_gervaz block turns an Ash resource into a create and edit form. This guide names the form, declares fields of several types, picks related records, edits nested shapes, groups the fields and sets the buttons. The examples come from the tags and blog posts forms of Mishka CMS and the component form of its page builder.

Before you begin

  • Add MishkaGervaz.Resource to the resource. See Get Started.
  • Have a create, an update and a read action, on the resource or named on the domain. A form with any field needs all three.

Name the form

The identity name is what MishkaGervaz.Resource.Info.Form.component_id/1 returns. Declare it, and mount the form with that id. Gervaz does not require the id, because the page that mounts the form chooses it.

elixir
form do
  identity do
    name :tag_form
  end
end

route is optional. Gervaz stores it, and the built-in form does not redirect with it.

Choose the actions and the preloads

The three form actions usually come from the domain. See How domain defaults work. In edit mode the form fetches the record with the read action. If a field reads a relationship, preload it by role, so that the master and tenant forms load different relationships. The blog post form does this for its collections, tags and bloggers:

elixir
source do
  preload do
    master [:master_collections, :master_tags, :master_bloggers]
    tenant [:tenant_collections, :tenant_tags, :tenant_bloggers]
  end
end

The read action of a preloaded relationship must set required?: false on its pagination, because a preload passes no page. Gervaz reports a violation when it compiles.

Declare fields

In the common case a field takes its type from the Ash attribute when you give none: a string is :text, a number is :number, a boolean is :checkbox, a date is :date and a datetime is :datetime. A string or atom attribute with constraints one_of: becomes a :select whose options Gervaz builds from the constraint. A long string, a UUID, a list and a map infer other types. Form fields DSL lists them all. Write options yourself to translate the labels, as the status field below does.

elixir
fields do
  field :title, :text do
    required true

    ui do
      label fn -> dgettext("mishka_gervaz", "Title") end
      placeholder fn -> dgettext("mishka_gervaz", "Post title") end
    end
  end

  field :status do
    options fn ->
      [
        {dgettext("mishka_gervaz", "Draft"), :draft},
        {dgettext("mishka_gervaz", "Published"), :published},
        {dgettext("mishka_gervaz", "Scheduled"), :scheduled}
      ]
    end

    ui do
      label fn -> dgettext("mishka_gervaz", "Status") end
    end
  end

  field :content, :textarea do
    required true

    ui do
      label fn -> dgettext("mishka_gervaz", "Content") end
      rows 8
    end
  end
end

A select draws an empty choice ahead of its options. The choice is labeled with ui placeholder when you set one. A required field or one with a default has no empty choice. Otherwise the choice reads "Select...".

Fields take these behavior options in the body, and presentation options in ui:

  • required, readonly, visible and restricted gate the field. readonly, visible and restricted take a boolean or a function of the state.
  • show_on :create or show_on :update shows the field in one mode.
  • virtual true marks a field that is not an attribute of the resource. default is stored with the field, and the built-in form uses it for one thing: a select with a default has no empty choice. Pass starting values with the defaults assign of the mount.
  • ui holds label, placeholder, description, icon, debounce, span, rows, autocomplete, add_label, remove_label, disabled_prompt, step, prefix, suffix, note, first_day_of_week and extra. The options class and wrapper_class are accepted, and the Standard form template does not read them.

A field the action neither accepts nor takes as an argument is drawn read-only and left out of the save. A value that is always written left to right, such as a slug, an address or a token, says so with ui do extra %{dir: "ltr"} end.

Choose one value from a few options

A :choice_cards field draws one radio per option as a card. A :segmented field draws the same choice as the segments of one bar, and suits two to four short options. An option is {label, value}, or a keyword list or map with :label, :value, :description (a second line under the label), :icon and disabled: true, which shows the option but does not let the reader pick it. options may also be a function of no arguments or of the form state, read each time the field is drawn.

elixir
field :kind, :choice_cards do
  options [
    [label: "One-time", value: :one_time, description: "Pay once, keep it", icon: "hero-bolt"],
    [label: "Subscription", value: :subscription, description: "Billed every period"]
  ]
end

field :billing, :segmented do
  options [{"Monthly", :monthly}, {"Yearly", :yearly}]
end

A :multi_select field draws one checkbox per option, and an option may carry a :description in the same way. The save sends the ticked values as a list, and an empty list when none is ticked.

Bound and shape a value

These field options and ui options shape what the reader can type:

  • min and max on a :number or :range field take an integer, a float or a Decimal, compared as Decimals. The input carries them with ui step, and a value outside them gets the error "is too small" or "is too large". A :number field draws and saves a Decimal.
  • min and max on a :date or :datetime field take a Date, DateTime or NaiveDateTime, or a function. The calendar greys out the days outside them, and a save with a value outside them gets "is too early" or "is too late". fn state -> value end receives the form state, and nil is no bound, so fn %{mode: :create} -> DateTime.utc_now(); _state -> nil end bounds only a new record.
  • The four messages, "is too small", "is too large", "is too early" and "is too late", are translated in the errors Gettext domain of your backend, as every other field error is.
  • ui step on a :datetime field is the minutes between the times its picker offers, and ui first_day_of_week is the day each week of a calendar starts on, Monday when not set.
  • max_length sets the most characters a text-like field takes, drawn as the input's maxlength. Without it the field takes the max_length constraint of its attribute.
  • ui prefix and ui suffix put a unit at the start or the end of a :text, :password or :number input, such as "USD" or "%". The unit is only shown and is not saved.
  • ui note on a :toggle or :checkbox field draws a sentence beside the control, inside its label. description stays the help text under any field, and it may be fn state -> text end.
  • live_errors true shows a field's own errors as it is typed, once it holds a value, in a form for a new record, which otherwise shows errors only after its first save.
elixir
field :price, :number do
  min Decimal.new("0.50")
  max Decimal.new("9999.99")

  ui do
    step 0.01
    prefix "USD"
  end
end

field :iban, :text do
  live_errors true
end

A :hidden field is drawn as a bare hidden input that carries its value. A field with ui do span 2 end, or 3 or 4, is the whole row below the breakpoint where the grid has that many columns, so on a phone it no longer squeezes the other fields.

Edit nested shapes

A :nested field edits an embedded resource or a constrained map column as repeatable rows. The rows are nested_field entities, which accept a narrower set of types: :text, :textarea, :number, :checkbox, :date, :datetime, :select, :hidden, :toggle, :range, :json, :key_map and :key_list.

elixir
field :seo_tags, :nested do
  ui do
    label fn -> dgettext("mishka_gervaz", "SEO Tags") end
    add_label fn -> dgettext("mishka_gervaz", "+ Add SEO Tag") end
    remove_label fn -> dgettext("mishka_gervaz", "Remove") end
  end

  nested_field :tag, :select do
    options [{"title", "title"}, {"meta", "meta"}, {"link", "link"}]

    ui do
      label fn -> dgettext("mishka_gervaz", "Tag") end
    end
  end

  nested_field :attrs, :json do
    ui do
      label fn -> dgettext("mishka_gervaz", "Attributes") end
    end
  end

  nested_field :content, :textarea do
    ui do
      label fn -> dgettext("mishka_gervaz", "Content") end
      rows 3
    end
  end
end

When the keys of a map are known and few, draw one control per key instead of asking for JSON. A :key_map edits one map, and a :key_list edits a list of maps with rows the reader adds and removes. Each key is a keyword list with a :name and, optionally, :type, :label, :placeholder, :options and :required. The :type is :text (the default), :textarea, :toggle, :checkbox, :number, :select, :json or :password. A :password key is drawn through the adapter's password_input with autocomplete off, and its value is never written back into the page, so a form that edits a record asks for it again. A :required key shows the required mark. A field of its own may also take options fn state -> keys end in place of the list. Gervaz reads it with the form state, so one form can draw different keys for different openings. The component form of the page builder declares a slot's options and attributes this way:

elixir
nested_field :opts, :key_map do
  options [
    [name: :required, type: :toggle, label: dgettext_noop("mishka_gervaz", "Required")],
    [name: :doc, type: :text, label: dgettext_noop("mishka_gervaz", "What goes in it")]
  ]

  ui do
    label fn -> dgettext("mishka_gervaz", "Options") end
  end
end

A blank key is left out of the stored map, and a toggle left off is left out too, so "not set" stays distinct from "set to nothing". Gervaz reports a nested_field outside a :nested field when it compiles.

Group the fields

Groups put fields in named sections and set the grid. A field may sit in one group. A field in no group still draws, but a wizard step can reach it only through a group. ui do columns N end sets the grid of one group, and layout do columns N end sets the default grid for the form.

elixir
groups do
  group :basic_info do
    fields [:site_id, :name, :slug, :language]

    ui do
      label fn -> dgettext("mishka_gervaz", "Basic Information") end
      columns 2
    end
  end

  group :organization do
    fields [:language_group_id, :parent_tag_id]

    ui do
      label fn -> dgettext("mishka_gervaz", "Organization") end
      columns 2
    end
  end
end

the Add Tag dialog opened from the Add Tag button, with the Basic Information group in two columns, the Organization group below it, then Details with Description, SEO Tags and Permissions

The tag form draws its groups in a two-column grid.

The example shows two groups. The real tag form has more under them: Details, which holds Description, and a last group of one-column fields for SEO Tags and Permissions.

Limit a field or a mode to masters

restricted true on a field, a group or a button limits it to master users. The tags form shows the site field to masters only, and only when a tag is created:

elixir
field :site_id, :relation do
  restricted true
  required true
  show_on :create
  display_field :name
  search_field :name
  mode :search
end

To close a whole mode, use source.access. The permissions form lets only masters create and update:

elixir
source do
  access :create, restricted: true
  access :update, restricted: true
end

access :update, false closes a mode for everyone, and then its action need not exist. A denied mode leaves the form without fields.

Set the buttons

The labels of the create, update and cancel buttons usually sit on the domain. A resource declares a submit section only where it differs, and the buttons merge one by one. See How domain defaults work.

A button label may be a function of the form state, so one form names its button for the action the mount asked for. A discard button draws beside Save while the form holds changes and puts the form back to its starting values. A confirm on a button asks first:

elixir
submit do
  update label: fn state -> if state.defaults[:ending], do: "End now", else: "Save changes" end
  cancel confirm: "Leave without saving?"
  discard label: "Discard"
end

A cancel or discard button asks its confirm only while the form holds changes. On create and update a keyword list asks in a question window, as Ask before an action shows. To place the groups in your own markup, draw the buttons yourself or learn when the form holds changes, see Place a form's groups in your page.

Explain a field with a notice

A notice in the layout draws a banner at a position. The page form of Mishka CMS shows help after the group that holds the field it explains, and only while that field is on the form:

elixir
layout do
  notice :permissions_help do
    position {:after_group, :access}
    show_when fn state -> Enum.any?(state.static.fields, &(&1.name == :permissions)) end

    render fn assigns ->
      ~H"""
      <MishkaCmsCore.CoreComponents.tip id="pb-permissions-help" class="mt-2.5 mb-4">
        {dgettext(
          "mishka_gervaz",
          "Who may open this page; empty means everyone. If the page shows records, leave it empty: each record's own Permissions are used."
        )}
      </MishkaCmsCore.CoreComponents.tip>
      """
    end
  end
end

Valid positions and bindings are listed in Form groups and layout DSL.

Next steps