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?
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 thechangeevent on corporation field, to filter the values ofchild_data