-1

假设我有数据:

data = [[key: 1, value: "1"], [key: 2, value: "2"] ,[key: 3, value: "3"]]
child_data = %{1: [key: 1, value: "exists"]}

和html:

<%= select f, :corporation_id, data %>
<%= select f, :company_id, child_data[Ecto.changeset.get_field(@changeset, :corporation_id)] %>

我的架构和变更集如下所示:

embedded_schema do
    field :corporation_id, :integer
    field :company_id, :integer
  end

def changeset(selected_org, attrs) do
    selected_org
    |> cast(attrs, [:corporation_id, :company_id])
    |> validate_required([:corporation_id, :company_id])
  end

问题如下:当我更改company变更集的数据时没有更新,旧的 id 仍然存在,它仍然是一个有效的变更集。据我了解,这是因为更新数据时没有发出验证事件。

这个问题有解决方法吗?

4

2 回答 2

0

好的,看起来这是当前 LiveView 的限制。使用 JS 中的更新挂钩,我能够将更新发送到服务器。钩子:

Hooks.WorkaroundHook = {
  updated() {
    this.pushEvent("workaround", this.el.selectedIndex)
  }
}

和手柄:

  def handle_event("workaround", index, socket) do
    # if changeset is valid and index is 0 add error to changeset
    {:noreply, socket}
  end
于 2020-10-07T08:14:35.010 回答
0

不幸的是,如果没有 JavaScript 或 Phoenix 的新 LiveView,您将无法完成您想要的工作。当您的模板被发送到浏览器时,您处理反应性的唯一方法是通过 JavaScript。在您的情况下,您需要做的是将所有 child_data 发送到 select: <%= select f, :company_id, child_data %>。然后使用 JavaScript,您change在公司字段上侦听事件,以过滤child_data

于 2020-10-05T18:11:26.753 回答