Image for post
Image for post

Chart.js in Elixir/Phoenix with Filtering

I was assigned to do the dashboard for this web application project were doing at my current job, and because it’s the dashboard, of course, you have charts. Considering that it’s just been months since I started doing backend stuff, I was quite pumped and curious on how to implement it on Elixir Phoenix (newbie alert 😂).

Image for post
Image for post

In this quick tutorial, I will show how to generate a chart with data coming from elixir/phoenix using poison. We will just focus on getting the , to make it quick and easy.

What we need:

Chart.js: You can install it using npm or bower here or use this cdnjs

Poison: a JSON library for Elixir

Applying Chart.js

We will be using the Line Chart in this example, it’s quite easy to apply.

in dashboard.html.eex

in dashboard.js

The bold part is the real data separated per month coming from the database, we will discuss that later on.

Getting the data

Now that we have a chart, let’s start getting the data, and since we have a filter , let’s take care of that first.

in dashboard.html.eex

It is a form get method as a query that has a select input passing year to our controller, will load the page and pass a query every time we select a year.

in dashboard_controller.ex

In the query we defined as default year incase is empty, this will happen every first-page load.

in inquiry_context.ex

In this method, the will get the year in and returns a float value, comparing it to the the variable will give us all the inquiries by year. We also grouped the result by month, and in the select part we use: to get the month part of , this will return , , etc. and then we count every record per month.

Image for post
Image for post
the result from the query

Mapping the data

We have the data, we just need to map them to our chart, and to do that we need poison.

in dashboard.html.eex

This code will allow us to access the data in our javascript file .

in dashboard.js

We loop the inquiries_per_month and assigned the to a variable separated by month using a switch case.

For the last part, we just have to put the variables to the chart’s dataset, the bold one we saw earlier.

in dashboard.js

And we’re done !!!!

result:

Image for post
Image for post

Hope this article reaches someone like me. Happy Coding!!

Check out the full story on my website: Chart.js in Elixir/Phoenix with Filtering

Elixir Developer — www.alvinrapada.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store