I have a Phoenix Liveview app that iterates through an Ecto collection named Testbed. The properties of Testbed are rendered to the Liveview via Heex and users can look at them . Some of these have event handlers that do stuff when people click on them.
I have another Ecto collection name Group. Group has a foreign key relationship with Testbed.
In my heex code I can access Group just like any other property on Testbed.
<th scope="col" class="px-6 rounded-l-full " phx-click="sort_by_string" phx-value-field="group">Group</th>
When a user clicks that DOM element it runs the sorting code below and phx-value-field=“group” is passed to the field property. The Testbeds are then sorted by Group.
If I passed name to the field property, the Testbeds would be sorted by their name.
def sort_by(socket, field) do
atomParam = String.to_existing_atom(field)
if socket.assigns[:sort_direction] == :desc do
sorted_testbeds = Enum.sort_by(socket.assigns.testbeds, fn item -> Map.get(item, atomParam) end)
{:noreply, assign(socket, testbeds: sorted_testbeds, sort_direction: :asc, sort_field: atomParam)}
else
sorted_testbeds = Enum.sort_by(socket.assigns.testbeds, fn item -> Map.get(item, atomParam) end)
|> Enum.reverse()
{:noreply, assign(socket, testbeds: sorted_testbeds, sort_direction: :desc, sort_field: atomParam)}
end
end
def handle_event("sort_by_string", %{"field" => field}, socket) do
sort_by(socket, field)
end
My problem is I explicitly want the Testbeds sorted by group.name
I am unsure how to access group.name in my current code or how to explicitly access any specific property on the Group. If I do: phx-value-field=“group.name” I am unsure if this is valid syntax to pass and if it is, how do I handle it and convert it to an atom so I can use it in my code?
My current code sorts the group but it does it in an oddball way where groups aren’t completely sorted alphabetically by name.