I’m reading the Context documentation trying to delve deeper into this subject.
Here it describes how to associate Categories to a Product (in my case, to a Business). I already have the basic struct using the LiveView and the doc is slightly different, as it is describing the process as the Controller structure.
Everything running good until this topic, where it asks to write the category_opts function inside ProductHTML view in lib/hello_web/controllers/product_html.ex file. But I don’t have this file (as I’m using the LiveView).
Here is the function provided by the documentation and I’m writing it on my form_component.ex:
def category_opts(changeset) do
existing_ids =
changeset
|> Ecto.Changeset.get_change(:categories, [])
|> Enum.map(& &1.data.id)
for cat <- Balaio.Catalog.list_categories(),
do: [key: cat.title, value: cat.id, selected: cat.id in existing_ids]
end
And the input field to present the data on the form (notice the changeset param):
The @ in @changeset is trying to read assigns.changeset bu you never assigned your changeset, just the formhere. But that’s ok—you don’t need to since the changeset is still accessible inside your @form assign via the source key.
If you want it to use your form assign with category_opts (which I agree would be better) just destructure source out of it. You can even rename it to changeset in the process so it’s clearer:
def category_opts(%{source: changeset} = _form) do