elixir - 如何清除 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
我尝试了几种不同的方法来解决这个问题,主要涉及支持表单的数据结构的变化。
- 我试过用地图支持表格。这是行不通的,因为表单必须由实现
Phoenix.HTML.FormData
协议的结构支持,而 Phoenix 只为Plug.Conn
和Atom
- 我尝试过使用结构,但这与地图的原因相同
- 我没有
Conn
在我的表单中使用,因为这是一个 LiveView,但我可以Conn
在 LiveView 控制器中创建一个,所以我做到了。我用它支持表单并在事件处理程序中传递一个新实例以进行后期创建。这并没有解决问题。 - 最后,我将其更改
textarea
为 atext_input
,并在提交表单时立即清除此输入。所以看起来问题是特定于textarea
元素的。我不确定这是否是 Phoenix 的错误。
解决方案
正如 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
推荐阅读
- node.js - Google 如何为我的 Google Assistant 创建音乐播放器
- php - Google App Engine 实例 - 奇怪的行为 PHP
- java - OpenSSH ecdsa 到 BCECPublicKey
- corda - 通过 RPC 获取关联的集合
- java - 如何将通用接口传递给它被具体化的方法?
- javascript - 访问通过 xhr 请求获取的 HTML 源中所有脚本标记中的变量
- javascript - Vue.js 2 和 Asp.Net MVC,如何在任何 *.ts、*.scss 和 *.vue 文件更改时启用自动重新加载?
- json - 格式化 SOLR 响应
- intellij-idea - 在 intellij 中清除“搜索所有内容”框
- python - python从csv文件头下拉