跳到内容

Symfony UX Chart.js

编辑此页

Symfony UX Chart.js 是一个 Symfony 扩展包,用于在 Symfony 应用程序中集成 Chart.js 库。 它是 Symfony UX 倡议的一部分。

安装

使用 Composer 和 Symfony Flex 安装扩展包

1
$ composer require symfony/ux-chartjs

如果您正在使用 WebpackEncore,请安装您的资源并重启 Encore (如果您正在使用 AssetMapper,则不需要)

1
2
$ npm install --force
$ npm run watch

用法

要使用 Symfony UX Chart.js,请注入 ChartBuilderInterface 服务并在 PHP 中创建图表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// ...
use Symfony\UX\Chartjs\Builder\ChartBuilderInterface;
use Symfony\UX\Chartjs\Model\Chart;

class HomeController extends AbstractController
{
    #[Route('/', name: 'app_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' => [
                'y' => [
                    'suggestedMin' => 0,
                    'suggestedMax' => 100,
                ],
            ],
        ]);

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

所有选项和数据都按原样提供给 Chart.js。 您可以阅读 Chart.js 文档以了解所有这些选项和数据。

一旦在 PHP 中创建,图表可以使用 Twig 显示

1
2
3
4
{{ render_chart(chart) }}

{# You can pass HTML attributes as a second argument to add them on the <canvas> tag #}
{{ render_chart(chart, {'class': 'my-chart'}) }}

使用插件

Chart.js 带有 许多插件来扩展其默认行为。 让我们看看如何按照 缩放插件文档使用缩放插件。

首先,安装插件

1
$ npm install chartjs-plugin-zoom -D

然后全局注册插件。 这可以在您的 app.js 文件中完成

1
2
3
4
5
6
7
8
9
10
// assets/app.js
import zoomPlugin from 'chartjs-plugin-zoom';

// register globally for all charts
document.addEventListener('chartjs:init', function (event) {
    const Chart = event.detail.Chart;
    Chart.register(zoomPlugin);
});

// ...

最后,使用图表选项配置插件。 例如,缩放插件文档显示了以下示例配置

1
2
3
4
5
6
7
8
9
10
11
12
13
// ...
options: {
    plugins: {
        zoom: {
            zoom: {
              wheel: { enabled: true },
              pinch: { enabled: true },
              mode: 'xy',
            }
        }
    }
}
// ...

要在 Symfony UX Chart.js 中使用相同的配置,您可以使用 setOptions() 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$chart = $chartBuilder->createChart(Chart::TYPE_LINE);

// ...

$chart->setOptions([
    'plugins' => [
        'zoom' => [
            'zoom' => [
                'wheel' => ['enabled' => true],
                'pinch' => ['enabled' => true],
                'mode' => 'xy',
            ],
        ],
    ],
]);

扩展默认行为

Symfony UX Chart.js 允许您使用自定义 Stimulus 控制器扩展其默认行为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// mychart_controller.js

import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
    connect() {
        this.element.addEventListener('chartjs:pre-connect', this._onPreConnect);
        this.element.addEventListener('chartjs:connect', this._onConnect);
    }

    disconnect() {
        // You should always remove listeners when the controller is disconnected to avoid side effects
        this.element.removeEventListener('chartjs:pre-connect', this._onPreConnect);
        this.element.removeEventListener('chartjs:connect', this._onConnect);
    }

    _onPreConnect(event) {
        // The chart is not yet created
        // You can access the config that will be passed to "new Chart()"
        console.log(event.detail.config);

        // For instance you can format Y axis
        // To avoid overriding existing config, you should distinguish 3 cases:
        // # 1. No existing scales config => add a new scales config
        event.detail.config.options.scales = {
            y: {
                ticks: {
                    callback: function (value, index, values) {
                        /* ... */
                    },
                },
            },
        };
        // # 2. Existing scales config without Y axis config => add new Y axis config
        event.detail.config.options.scales.y = {
            ticks: {
                callback: function (value, index, values) {
                    /* ... */
                },
            },
        };
        // # 3. Existing Y axis config => update it
        event.detail.config.options.scales.y.ticks = {
            callback: function (value, index, values) {
                /* ... */
            },
        };
    }

    _onConnect(event) {
        // The chart was just created
        console.log(event.detail.chart); // You can access the chart instance using the event details

        // For instance you can listen to additional events
        event.detail.chart.options.onHover = (mouseEvent) => {
            /* ... */
        };
        event.detail.chart.options.onClick = (mouseEvent) => {
            /* ... */
        };
    }
}

然后在您的渲染调用中,将您的控制器添加为 HTML 属性

1
{{ render_chart(chart, {'data-controller': 'mychart'}) }}

还有一个 chartjs:init 事件,它在您的第一个图表渲染之前仅调用一次。 这是全局注册 Chart.js 插件或对 Chart.js 的任何“静态”/全局部分进行其他更改的理想位置。 例如,添加全局 Tooltip 定位器

1
2
3
4
5
6
7
8
9
10
// assets/app.js

// register globally for all charts
document.addEventListener('chartjs:init', function (event) {
    const Chart = event.detail.Chart;
    const Tooltip = Chart.registry.plugins.get('tooltip');
    Tooltip.positioners.bottom = function(items) {
        /* ... */
    };
});

向后兼容性承诺

此扩展包旨在遵循与 Symfony 框架相同的向后兼容性承诺:http://symfony.ac.cn/doc/current/contributing/code/bc.html

这项工作,包括代码示例,均根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本