Daniel
Daniel

Reputation: 2554

Changeset not updating on dropdown data update

Suppose I have the data:

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

And the html:

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

My schema and changeset looks the following:

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

The problem is the following: When I change the data of company the changeset does not get updated, the old id remains and it is still a valid changeset. As far as I understand this happens because no validate event is emitted when the data is updated.

Is there a workaround for this issue?

Upvotes: -1

Views: 416

Answers (2)

Daniel
Daniel

Reputation: 2554

Okay looks like this is a limitation of LiveView currently. Using an update hook in JS I was able to send the update to the server. The hook:

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

And the handle:

  def handle_event("workaround", index, socket) do
    # if changeset is valid and index is 0 add error to changeset
    {:noreply, socket}
  end

Upvotes: 0

franckstifler
franckstifler

Reputation: 396

Unfortunately, you can't accomplish what you want without JavaScript, or the new LiveView from Phoenix. As your template is sent to the browser, the only way for you to handle reactivity is through JavaScript. In your case, what you need to do is send all the child_data to the select: <%= select f, :company_id, child_data %>. Then using JavaScript, you listen to the change event on corporation field, to filter the values of child_data

Upvotes: 0

Related Questions