首页 > 解决方案 > 如何清除 Phoenix LiveView 表单中的文本区域?

问题描述

我有一个 Phoenix LiveView,其表单不受数据层支持,如下所示:

<%= f = form_for :post, "#", [phx_submit: :create_post %>
  <%= textarea f, :message, placeholder: "Say something:" %>
  <%= hidden_input f, :user_id, value: @current_user.account_id %>
  <%= submit "Post" %>
</form>

我无法使用变更集支持表单,因为我没有使用 Ecto。提交表单后,提交处理就好了,但是表单textarea没有被清除。如何在不使用 Javascript 的情况下清除输入?

如果没有 Javascript 就无法做到这一点,我如何使用Javascript 做到这一点,但又不绕过 LiveViewphx-submit机制?

一些额外的故障排除信息:

这是我的事件处理程序:

def handle_event("create_post", %{"post" => post_params}, socket) do
  thread_id = socket.assigns.thread.id
  user_id = post_params["user_id"]
  posts = Forums.append_post!(thread_id, user_id, post_params)
  UdsWeb.Endpoint.broadcast_from(self(), build_topic(thread_id), "new_post", %{posts: posts})
  {:noreply, assign(socket, :posts, posts)}
end

我尝试了几种不同的方法来解决这个问题,主要涉及支持表单的数据结构的变化。

标签: elixirphoenix-frameworkphoenix-live-view

解决方案


正如 Aleksei 在他的评论中所说:您必须将一个新Post结构从您的控制器传递到您的视图。例如像这样:

def handle_event("create_post", post, socket) do
    # Here do what you want with the data from the "post" parameter

    {:noreply, assign(socket, :post, %Post{})}   
end

推荐阅读