ash-project / ash_phoenix

Utilities for integrating Ash and Phoenix

Home Page:https://hexdocs.pm/ash_phoenix

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

AshPhoenix.Form doesn't mesh well with default resource values

brettkolodny opened this issue · comments

When submitting a form outside of LiveView Phoenix will populate unfilled form values with "". Even if the given resource has default values after calling AshPhoenix.Form.submit what ends up being created is resource with attributes with the value of "". Furthermore if allow_nil? false is set then the validation will also fail. This leads to a situation where default values need to be manually set before validating and submitting the form even though the attribute has a default value set.

Example Controller

def new(conn, %{"new_list" => params}) do
    Todoish.Entries.List
    |> AshPhoenix.Form.for_create(:create,
      api: Todoish.Entries,
      transform_params: fn params, _ ->
        # Manually set default
        params =
          if params["title"] in ["", nil] do
            Map.put(params, "title", "A Todoish List")
          else
            params
          end

        params =
          # Manually set default
          if params["description"] in ["", nil] do
            Map.put(params, "description", "Add items to get started!")
          else
            params
          end

        Map.put(params, "url_id", Nanoid.generate())
      end
    )
    |> AshPhoenix.Form.validate(params)
    |> AshPhoenix.Form.submit()
    |> case do
      {:ok, result} ->
        IO.inspect(result)
        redirect(conn, to: "/#{result.url_id}")

      {:error, form} ->
        IO.inspect(form)

        conn
        |> put_flash(:error, "Uh-oh! Something went wrong. Please try again!")
        |> render("index.html", form: form)
    end
  end

Expected behavior
It would be ideal if there was a way to submit a form such that the default values of the attribute itself can be used instead of needing to manually check and fill them prior to submitting/validating the form.

I'm thinking that the simple answer here is that there is some option like empty_fields_unset: [:title, :description].

Would generally only be necessary to use when not using live_view

I think that would be good because it could be used to both validate required values if no default or just use the default for the attribute