I am trying to replicate the UX which can be done with mix phx.gen.html
in a normal Phoenix setup with Ash. It is a bit of a struggle. I can’t find an example.
I have a product:
attributes do
uuid_primary_key :id
attribute :name, :string do
allow_nil? false
end
attribute :price, :integer do
allow_nil? false
constraints min: 0
end
end
I have a controller with these functions:
def edit(conn, %{"id" => id}) do
product = Product.by_id!(id)
form =
AshPhoenix.Form.for_update(product, :update, actor: nil, api: App.Shop)
render(conn, :edit, product: product, form: form)
end
def update(conn, %{"form" => product_params, "id" => id}) do
product = Product.by_id!(id)
case Product.update(product, product_params) do
{:ok, product} ->
conn
|> put_flash(:info, "Product updated successfully.")
|> redirect(to: ~p"/products/#{product}")
{:error, %Ash.Error.Invalid{changeset: changeset}} ->
form =
AshPhoenix.Form.for_update(changeset.data, :update, actor: nil, api: App.Shop)
conn
|> put_flash(:error, "Product could not be updated.")
|> render(:edit, product: changeset.data, form: form)
end
end
And the template:
<.header>
Edit Product <%= @product.id %>
<:subtitle>Use this form to manage product records in your database.</:subtitle>
</.header>
<.simple_form :let={f} for={@form} action={~p"/products/#{@product}"}>
<.input field={f[:name]} type="text" label="Name" />
<.input field={f[:price]} type="number" label="Price" step="any" />
<:actions>
<.button>Save Product</.button>
</:actions>
</.simple_form>
<.back navigate={~p"/products"}>Back to products</.back>
In the Phoenix world the form would include this:
<.error :if={@changeset.action}>
Oops, something went wrong! Please check the errors below.
</.error>
And would display the validation errors while doing an update. How can I do this or something similar in Ash?