phoenix-framework - 如何使用 Phoenix LiveView 处理表单
问题描述
我在凤凰城有一个看起来像这样的表格
<%= form_for @changeset, Routes.post_path(@conn, :create, @post), [method: "post", multipart: true], fn f -> %>
<div class="row mt-3">
<div class="form-group col-6">
<%= input f, :title, "Title", [class: "form-control", type: "text", placeholder: "Enter Title", required: true] %>
</div>
<div class="form-group col-6">
<%= input f, :description, "Description", [class: "form-control", type: "text", placeholder: "Enter Description", required: true] %>
</div>
</div>
<div class="d-flex mt-3">
<%= submit "Create Post" %>
</div>
<% end %>
上面的表格工作正常,现在我想改变这个表格来实现 LiveView。所以我做了这样的事情
<%= form_for @changeset, "#", [method: "post", multipart: true], fn f -> %>
<div class="row mt-3">
<div class="form-group col-6">
<%= input f, :title, "Title", [class: "form-control", type: "text", placeholder: "Enter Title", required: true] %>
</div>
<div class="form-group col-6">
<%= input f, :description, "Description", [class: "form-control", type: "text", placeholder: "Enter Description", required: true] %>
</div>
</div>
<div class="d-flex mt-3">
<button phx-click="create-post" phx-value="form-value">Create Post"</button>
</div>
<% end %>
我很困惑form-value
,需要发送什么,以便我将获得包含title
和description
在我的handle_event
函数中的正确表单数据。
我尝试传递@changeset
and f
,但他们正在发送正确的phx-value
,其中将包含我的title
and description
。
不确定,如果使用 LiveView 正确实现 Form,或者需要以不同的方式完成。
解决方案
这里唯一的区别是您不想将匿名函数与 form_for 一起使用。
<%= form_for @changeset, "#", [phx_submit: "post", multipart: true], fn f -> %>
...
<% end %>
变成
<%= f = form_for @changeset, "#", [phx_submit: "post", multipart: true] %>
...
</form>
匿名函数内容无法区分。
推荐阅读
- php - PHP如何包含饼图
- oracle - 向 oracle 表添加参考分区
- python-3.x - 如何在 Python 中使用 Selenium Webdriver 在一个页面中处理具有相同类的更多元素
- http - 如何在颤动中使用 DIO 将多个文件、文件列表发布到服务器
- java - 未能执行目标 org.apache.maven.plugins:maven-compiler-plugin:3.8.1
- python - Python text out of TD error 'NoneType' object has no attribute 'text' 为什么?
- amazon-iam - 从命令行获取 AWS 访问密钥
- mysql - 按日期排序后如何按名称使用 ORDER?
- websocket - Deno:如何将 WebSocket 与橡木一起使用?
- javascript - 无法使用 onChangeText 更新反应原生组件中的状态