【问题标题】:Phoenix HTML - how to generate nested formPhoenix HTML - 如何生成嵌套表单
【发布时间】:2017-03-25 18:58:57
【问题描述】:

我来自 PHP Symfony2 框架。假设您有模型UserAddress

schema "users" do
  field :name, :string
  has_many :addresses, App.Address
end
schema "addresses" do
  field :street, :string
  field :city, :string
  ...
  belongs_to :user, App.User
end

我想用多个 Address 子表单为 User 创建表单。我已经阅读了Working with Ecto associations and embeds,它描述了如何从集合中编辑和删除项目。但是动态添加新的并没有什么,我的意思是为新的Address 生成一个子表单。在 Symfony 中有一个叫做 "prototype" 的东西,这是一个简单的函数,可以为集合中的项目生成表单。它生成名称为name="addresses[__name__][city]" 的输入。然后我需要用集合中项目的正确索引替换 JS __name__。我在凤凰城没有找到任何类似的东西。

我做了一个丑陋的代码,其工作方式类似于 Symfony 的方式:

<% {:safe, prototype}
  = form_for App.User.changeset(
      %App.User{addresses: [%App.Address{}]}
    ), "", fn f2 ->
    inputs_for f2, :addresses, fn i2 ->
      render("form_address.html", i: i2)
    end
  end
%>

<div data-prototype="<%= prototype %>">
  <%= inputs_for f, :addresses, fn i -> %>
    <%= render "form_address.html", i: i %>
  <% end %>
</div>

<button type="button">
  Add address
</button>

当我点击添加地址 JS 用适当的索引替换输入属性(例如name="addresses[0][city]")中的[0]_0_,并在集合中添加新项目。它有效,但是有什么正确的方法吗?

【问题讨论】:

  • 我认为这个其他问题可能会对您有所帮助stackoverflow.com/questions/32054561/…
  • @neydroid 对这个问题的回答是关联 1-1,在控制器中硬编码一个 Engine 到一个 Car,因此 Phoenix 能够很好地生成这个子表单。我需要通过 JavaScript 动态添加一个新的子表单来关联 1-many。

标签: elixir phoenix-framework


【解决方案1】:

我为 Phoenix 创建了自己的表单库 - Formex。它支持nested formscollections of forms,即one_to_oneone_to_many关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多