Suggestion needed: show dynamic chart in popover

Hi team,

The requirement is, there is a column in the datagrid showing sum of subtypes of current row, while click on the number, a popover should be displayed to show a pie chart of all subtypes.

Vaadin’s Popover can be used here, but I have no idea how to add the pie chart dynamically into the popover? Could you please share example code?

Hi!

You can try something like this:

    @ViewComponent
    private Span span;
    @Autowired
    private UiComponents uiComponents;

    @Subscribe
    public void onInit(InitEvent event) {
        Popover popover = new Popover();
        popover.setTarget(span);

        popover.addOpenedChangeListener(openedEvent -> {
            if (openedEvent.isOpened()) {
                openedEvent.getSource().add(createChart());
            } else {
                openedEvent.getSource().removeAll();
            }
        });

    }

    private Chart createChart() {
        Chart chart = uiComponents.create(Chart.class);

        chart.setId("chart");
        chart.setHeight("20em");
        chart.setWidth("20em");

        chart.withLegend(new Legend())
                .withSeries(new PieSeries()
                        .withStartAngle(45));

        ListChartItems<MapDataItem> items = createChartDataItems();
        chart.withDataSet(
                new DataSet().withSource(
                        new DataSet.Source<MapDataItem>()
                                .withDataProvider(items)
                                .withCategoryField("description")
                                .withValueField("value")
                )
        );

        return chart;
    }

    private ListChartItems<MapDataItem> createChartDataItems() {
        return new ListChartItems<>(
                new MapDataItem(Map.of("value", 75, "description", "Sky")),
                new MapDataItem(Map.of("value", 7, "description", "Shady side of pyramid")),
                new MapDataItem(Map.of("value", 18, "description", "Sunny side of pyramid"))
        );
    }

Unfortunately, the chart has to be added after the popover is opened because the component needs to know the size of the parent container in order to render correctly. More details can be found in the following comment: Jmix Chart inside Details Element · Issue #4728 · jmix-framework/jmix · GitHub

Best regards,
Dmitriy