我正在抓狂,因为我知道我可能遗漏了一些非常小的东西,但我只是想在成功提交表单后清除表单——一个要点创建成功,没有任何问题。
这是我的简单的 create_gist_live.ex 文件:
defmodule ElixirGistWeb.CreateGistLive do
use ElixirGistWeb, :live_view
import Phoenix.HTML.Form
alias ElixirGist.{Gists, Gists.Gist}
def mount(_params, _session, socket) do
socket =
assign(
socket,
form: to_form(Gists.change_gist(%Gist{}))
)
{:ok, socket}
end
def handle_event("create", params, socket) do
case Gists.create_gist(socket.assigns.current_user, params["gist"]) do #passing params["gist"] is so so necessary. I was stuck for a day just passing params at first
{:ok, _gist} ->
changeset = Gists.change_gist(%Gist{})
socket =
socket
|> put_flash(:info, "Gist created successfully.")
|> assign(:form, to_form(changeset))
{:noreply, socket}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset))}
end
end
end
然后这是相应的.html.heex 文件:
<div class="em-gradient flex items-center justify-center">
<h1 class="font-brand font-bold text-3xl text-white">
Instantly share Elixir code, notes, and snippets.
</h1>
</div>
<.form for={@form} phx-submit="create">
<div class="justify-center px-28 w-full space-y-4 mb-10">
<.input field={@form[:description]} placeholder="Gist description.." autocomplete="off"/>
<div>
<div class="flex p-2 items-center bg-emDark rounded-t-md border">
<div class="w-[300px] mb-2">
<.input field={@form[:name]} placeholder="Filename including extension..." autocomplete="off"/>
</div>
</div>
<.input
field={@form[:markup_text]}
type="textarea"
placeholder="Insert code..."
spellcheck="false"
autocomplete="off"
/>
</div>
<div class="flex justify-end">
<.button class="create_button">Create gist</.button>
</div>
</div>
</.form>
表单正常工作,因为在填写所有字段后数据会持久保存到 postgres 数据库中。如果缺少字段,我们会收到验证错误。但我就是无法在成功提交后清除表单。我以为我做了正确的事情,即创建一个空白的 Gist 变更集并将其分配给表单,但由于某种原因,这不起作用。