如何使用Phoenix LiveView处理表单

时间:2019-04-17 10:54:23

标签: phoenix-framework

我在凤凰城有一个看起来像这样的表格

<%= 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中的descriptionhandle_event功能。

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

不确定,如果要使用LiveView正确实现Form或需要以其他方式完成

2 个答案:

答案 0 :(得分:1)

这里唯一的区别是您不想在form_for中使用匿名函数。


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

成为

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

不能区分匿名函数的内容。

答案 1 :(得分:0)

这是使用phoenix liveview实施表单的正确方法

<%= form_for @changeset, "#", [phx_submit: "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", phx_disable_with: "Posting..." %>
    </div>
<% end %>