diff --git a/lib/components_elixir_web/live/categories_live.ex b/lib/components_elixir_web/live/categories_live.ex index c3cdcec..12062ed 100644 --- a/lib/components_elixir_web/live/categories_live.ex +++ b/lib/components_elixir_web/live/categories_live.ex @@ -44,7 +44,14 @@ defmodule ComponentsElixirWeb.CategoriesLive do def handle_event("show_edit_form", %{"id" => id}, socket) do category = Inventory.get_category!(id) - changeset = Inventory.change_category(category) + # Create a changeset with current values forced into changes for proper form display + changeset = Inventory.change_category(category, %{ + name: category.name, + description: category.description, + parent_id: category.parent_id + }) + |> Ecto.Changeset.force_change(:parent_id, category.parent_id) + form = to_form(changeset) {:noreply, @@ -127,15 +134,15 @@ defmodule ComponentsElixirWeb.CategoriesLive do [{"No parent (Root category)", nil}] ++ available_categories end - defp is_descendant?(categories, potential_ancestor_id, category_id) do - # Prevent circular references by checking if the potential parent is a descendant - category = Enum.find(categories, fn cat -> cat.id == category_id end) + defp is_descendant?(categories, descendant_id, ancestor_id) do + # Check if descendant_id is a descendant of ancestor_id + descendant = Enum.find(categories, fn cat -> cat.id == descendant_id end) - case category do + case descendant do nil -> false %{parent_id: nil} -> false - %{parent_id: parent_id} when parent_id == potential_ancestor_id -> true - %{parent_id: parent_id} -> is_descendant?(categories, potential_ancestor_id, parent_id) + %{parent_id: parent_id} when parent_id == ancestor_id -> true + %{parent_id: parent_id} -> is_descendant?(categories, parent_id, ancestor_id) end end