Table Filter with Phoenix LiveView

Isaac Martinat
2 min readMay 22, 2019

--

Part 2 : How to filter columns with dropdown lists

Part 1 explains how the user can select the columns to be visible on the table. In this part, we will explain how to filter columns using dropdown lists.

Here is the template, for each column, if this column is in the list of filtered columns filter_list (line 28), then it shows a dropdown list of values for this column. We use a map select containing the list of the values for each column, so we use Map.get on this map to get the list for a specific column col (lines 31–32).

In the function mount (modified a little bit from part 1 to clean the code to get the rows and the column list from functions), we set filter_list and select that we use in our template. We also set a map filter containing all the filters, the values selected by the user from the dropdown lists. In the mount function filter is a map containing for each filtered column the value “All”.

Then here are the different additional clauses for handle_event. In our template we have a “reset” button that the clause handle_event “reset” puts back in the map filter the value “All” for each column.

The clause handle_event “filter” get the value val from the map filter received by this function. If the value selected by the user is “All” we remove the previous filter with the same key, if a previous value was selected for this column, then it needs to be deleted. If it’s not “All”, we merge this filter to the socket.assigns.filter . Then we use get_filter_rows that runs a query to the database using this new_filter.

get_filter_rows calls query_table from the context file reusing the same code for compose_query from https://elixirschool.com/blog/ecto-query-composition/ . We also update select, the map containing the values for the dropdown lists. For example if you select France in the country column, you want to see only the french cities in the dropdown list for the column City.

You can find the full Phoenix code on github. The full code for this template is here. You can also find the code for the Part 3.

It was really fun to add this feature in Phoenix LiveView without writing any Javascript.

I wrote quickly this article, so please let me know in the comments if something is not clear or needs more explanations. I hope you enjoy or will enjoy using Phoenix LiveView. Please let me know also if you have more general questions about Phoenix LiveView.

--

--