Corex.DataTable.Sort
(Corex v0.1.0-alpha.33)
View Source
Helpers for sortable .data_table usage in LiveViews.
Use in mount to assign initial sort state and sorted rows, and in handle_event("sort", ...) to update sort and re-sort the rows assign. Keeps the LiveView minimal: no manual sort_by/sort_order or sort logic.
Example
def mount(_params, _session, socket) do
socket =
socket
|> assign(:users, fetch_users())
|> Corex.DataTable.Sort.assign_for_sort(:users, default_sort_by: :id, default_sort_order: :asc)
{:ok, socket}
end
def handle_event("sort", params, socket) do
{:noreply, Corex.DataTable.Sort.handle_sort(socket, params, :users)}
end
def render(assigns) do
~H"""
<.data_table
id="users-table"
rows={@users}
sort_by={@sort_by}
sort_order={@sort_order}
on_sort="sort"
>
<:col :let={user} label="ID" name={:id}>{user.id}</:col>
<:col :let={user} label="Name" name={:name}>{user.name}</:col>
</.data_table>
"""
end
Summary
Functions
Assigns sort state and sorts the given rows assign for initial render.
Handles the "sort" event and returns the updated socket.
Functions
Assigns sort state and sorts the given rows assign for initial render.
Use in mount/3 after assigning the list. Options:
:default_sort_by– atom, column to sort by (e.g.:id):default_sort_order–:ascor:desc, default:asc
The socket must already have an assign at rows_assign (e.g. :users)
with a list of maps. Adds or updates :sort_by, :sort_order, and
replaces the rows assign with the sorted list.
Handles the "sort" event and returns the updated socket.
Use in handle_event("sort", params, socket) and return
{:noreply, Corex.DataTable.Sort.handle_sort(socket, params, :users)}.
params must contain "sort_by" (string, e.g. "id"). It is converted
to an atom. rows_assign is the assign key holding the list (e.g. :users).