Corex. DataTable. Sort
(Corex v0.1.0-rc.1)
View Source
Helpers for sortable data_table/1 usage in LiveViews.
Use with Corex.DataTable: set sort_by, sort_order, on_sort, and
a name on each sortable column (see the Sortable pattern in
data_table/1 docs). In the LiveView, call
assign_for_sort/3 in mount/3, then handle_sort/3 from the on_sort event handler.
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 rows for a data_table/1 instance.
Handles the on_sort event from data_table/1 and returns the updated socket.
Functions
Assigns sort state and sorts the rows for a data_table/1 instance.
Use in mount/3 after assigning the list. Options:
:default_sort_by– atom; columnnameondata_table/1(e.g.:id):default_sort_order–:ascor:desc, default:asc
The socket must already have an assign at rows_assign (e.g. :users) with the same list
passed as rows to data_table/1. Adds :sort_by,
:sort_order, and replaces the rows assign with the sorted list.
Handles the on_sort event from data_table/1 and returns the updated socket.
Use in handle_event("sort", params, socket) (same name as on_sort) 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 passed to data_table/1 as rows.