30/04/2021

Faire des beaux graphiques avec symfony et chartjs

Installer yarn :

apt install yarn

Si ça marche pas :

sudo apt remove cmdtest
sudo apt remove yarn
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update
sudo apt-get install yarn -y
composer require symfony/ux-chartjs
yarn install --force

Installer encore

composer require symfony/webpack-encore-bundle
yarn install



yarn add --dev @symfony/webpack-encore

yarn add webpack-notifier --dev

yarn encore dev

Lancer le serveur de test

yarn run dev-server
OU

dev-server --public http://10.0.30.243:8080 --host 0.0.0.0

Build

yarn buil

Code

Controller

// ...
use Symfony\UX\Chartjs\Builder\ChartBuilderInterface;
use Symfony\UX\Chartjs\Model\Chart;

class HomeController extends AbstractController
{
    /**
     * @Route("/", name="homepage")
     */
    public function index(ChartBuilderInterface $chartBuilder): Response
    {
        $chart = $chartBuilder->createChart(Chart::TYPE_LINE);
        $chart->setData([
            'labels' => ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
            'datasets' => [
                [
                    'label' => 'My First dataset',
                    'backgroundColor' => 'rgb(255, 99, 132)',
                    'borderColor' => 'rgb(255, 99, 132)',
                    'data' => [0, 10, 5, 2, 20, 30, 45],
                ],
            ],
        ]);

        $chart->setOptions([
            'scales' => [
                'yAxes' => [
                    ['ticks' => ['min' => 0, 'max' => 100]],
                ],
            ],
        ]);

        return $this->render('home/index.html.twig', [
            'chart' => $chart,
        ]);
    }
}

Vue

{% block javascripts %}
  	{{ encore_entry_script_tags('app') }}
{% endblock %}
{% block stylesheets %}
	  	{{ encore_entry_link_tags('app') }}
{% endblock %}

{{ render_chart(chart, {'class': 'my-chart'}) }}