[英]Phoenix LiveView Nested Associations Form
I'm experimenting with Phoenix 1.6 and LiveView, and trying to get my nested form/models to work as expected.我正在试验 Phoenix 1.6 和 LiveView,并试图让我的嵌套表单/模型按预期工作。
I have a schema with something like: Parent
, Child
, where Parent has_many Children // Child belongs_to parent.我有一个类似这样的模式:
Parent
, Child
,其中 Parent has_many Children // Child belongs_to parent。
I want to have something like an Add Child button, which will render another Child model in my form in the inputs_for block, that I can make changes to, and eventually submit.我想要一个类似 Add Child 按钮的东西,它将在 inputs_for 块中的表单中呈现另一个 Child model,我可以对其进行更改并最终提交。
I've tried a handful of things such as https://fullstackphoenix.com/tutorials/nested-model-forms-with-phoenix-liveview , but they either don't seem to work, or seem a bit outdated (referencing things that don't exist for me).我已经尝试了一些东西,例如https://fullstackphoenix.com/tutorials/nested-model-forms-with-phoenix-liveview ,但它们似乎不起作用,或者看起来有点过时(参考东西对我来说不存在)。 The documentation helps a little bit, but doesn't seem to connect the Ecto bits with the LiveView bits that I'm looking for very well.
该文档有一点帮助,但似乎没有将 Ecto 位与我正在寻找的 LiveView 位联系起来。 Does anyone have thoughts/advice on the best way to achieve what I'm looking for?
有没有人对实现我正在寻找的最佳方式有想法/建议? (I'm also a bit newer to Elixir/Phoenix/Ecto, so there may be things that I'm overlooking)
(我对 Elixir/Phoenix/Ecto 也比较陌生,所以我可能忽略了一些东西)
I don't know if you're still struggling with this but I made it work some time ago.我不知道你是否还在为此苦苦挣扎,但我前段时间让它工作了。 I was working on some e-commerce application prototype and found the same post you shared.
我正在研究一些电子商务应用程序原型,并发现了您分享的相同帖子。
Here's a form_component example that uses the variants concept. 这是一个使用变体概念的 form_component示例。 If you use Phoenix 1.5 you can look a few commits back before the migration to
.heex
happened.如果您使用 Phoenix 1.5,您可以在迁移到
.heex
之前查看一些提交。
I could give you some more advice if you share a bit of code where the problem resides.如果您分享一些问题所在的代码,我可以给您更多建议。
This is a basic example.这是一个基本的例子。
<.icon phx-click="add_row" phx-value-id={f.data.id}
...
def handle_event("add_row", %{"id" => id}, socket) do
%{changeset: changeset, parent: parent} = socket.assigns
l = length(parent.childs)
new_child = %Child{order: l, parent_id: id}
childs =
changeset.changes
|> Map.get(:childs, parent.childs)
|> Enum.concat([new_child])
parent = Map.put(parent, :childs, childs)
{:noreply,
socket
|> update(:changeset, fn changeset ->
Ecto.Changeset.put_assoc(changeset, :childs, childs)
end)
|> assign(:parent, parent)}
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.