I am rendering a form related to this schema in a live view:
defmodule Storybook.Examples.Schemas.Person do
use Ecto.Schema
import Ecto.Changeset
embedded_schema do
field(:avatar, :string)
end
def changeset(user, attrs \\ %{}) do
user |> cast(attrs, [:avatar]) |> validate_required([:avatar])
end
end
The avatar field should be the path of an uploaded file.
In the template of the live view I binded the phx-change and phx-submit events like it’s explained here: Uploads — Phoenix LiveView v0.18.18
What I am not getting is how to validated the fact that the :avatar field is required.
In the phx-change callback I don’t get it in the params.
I hope I’ve been clear enough about my goal, otherwise I can paste some more code.
def handle_event("save", product_params, socket) do
file_path =
consume_uploaded_entry(socket, :image, fn %{path: path}, _entry ->
dest = Path.join("priv/static/uploads", Path.basename(path))
File.cp!(path, dest)
Routes.static_path(socket, "/uploads/#{Path.basename(dest)}")
end)
# This is where the form parameters have the filename added
# save_product will go and do the changeset and Repo saving bits
product = save_product(Map.put(product_params, :image_upload, file_path)
{:noreply,
socket
|> push_redirect(to: Routes.product_show_path(socket, :show, product))}
end