【问题标题】:Changeset not updating on dropdown data update更改集未在下拉数据更新时更新
【发布时间】:2020-10-07 16:14:35
【问题描述】:

假设我有数据:

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 仍然存在,它仍然是有效的变更集。据我了解,这是因为更新数据时没有发出验证事件。

这个问题有解决办法吗?

【问题讨论】:

    标签: elixir phoenix-framework liveview


    【解决方案1】:

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

    【讨论】:

    • 我已经在使用 liveview,请注意标签
    【解决方案2】:

    好吧,这似乎是 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      相关资源
      最近更新 更多