首页 > 解决方案 > 如何使用 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,需要发送什么,以便我将获得包含titledescription在我的handle_event函数中的正确表单数据。

我尝试传递@changesetand f,但他们正在发送正确的phx-value,其中将包含我的titleand description

不确定,如果使用 LiveView 正确实现 Form,或者需要以不同的方式完成。

标签: phoenix-framework

解决方案


这里唯一的区别是您不想将匿名函数与 form_for 一起使用。


<%= form_for @changeset, "#", [phx_submit: "post", multipart: true], fn f -> %>
...
<% end %>

变成

<%= f = form_for @changeset, "#", [phx_submit: "post", multipart: true] %>
...
</form>

匿名函数内容无法区分。


推荐阅读