How to Add a Legend to a Doughnut Chart in Creatio Freedom UI Using JavaScript?

How to Add a Legend to a Doughnut Chart in Creatio Freedom UI Using JavaScript?

Hi Creatio Community,

I'm working on a doughnut chart in Creatio Freedom UI and would like to display a legend below the chart. However, the chart configuration available in the Freedom UI designer does not provide an option to enable the legend for a doughnut chart.

I would like to explore whether this can be achieved through a client-side JavaScript handler without modifying the underlying chart configuration or affecting the chart's existing functionality.

  • Chart element: HTML inside the ts-chart component
  • Requirement: Display a custom legend below the doughnut chart, showing each series' actual color and label.

Questions:

  1. Is there a supported way to enable or configure a legend for a doughnut chart in Creatio Freedom UI?
  2. If the designer does not support this option, can a custom legend be added using a Freedom UI client-side JavaScript handler?
  3. How can we access the chart's actual labels, dataset values, and colors from the ts-chart component or its underlying chart configuration?
  4. Is there a recommended or supported API for accessing the chart instance without relying on undocumented internal properties?

My preference is to display the legend below the doughnut chart, using the existing chart labels and colors, while keeping the implementation scoped to this widget and preserving its existing interactions.

Any guidance, examples, or recommended approaches would be appreciated.

Thank you!

Like 0

Like

1 comments

Hi,

Thank you for the detailed question. Here are answers to each point, followed by the approach we recommend.

1. Is there a supported way to enable a legend for a doughnut chart?

Unfortunately, no. This is a current platform limitation, not a setting the Freedom UI Designer is missing.

  • The Show legend option is available only for Spline, Line, Bar, Area, Column and Scatter charts. Pie and doughnut charts don’t support a legend.
  • If you add a legend setting to the doughnut series by editing the page schema, the page saves it, but no legend appears. The chart turns off the legend for pie, doughnut, funnel and waterfall charts.
  • You can’t set slice colors either. The series color property is ignored for doughnut charts, and slices take their colors from the built-in palette.

What doughnut charts do show is a “label – NN%” data label next to each slice by default. Long labels wrap. Labels that would overlap are hidden, so very small slices may have no label. The dataLabel.display setting has no effect on doughnut charts.

2. Can a custom legend be added with client-side code?

Yes, as a separate element placed directly under the chart. It can’t be drawn inside the chart, because the chart is a single <canvas> with no extension point for that. This approach leaves the chart widget unchanged, so drilldown, tooltips, data labels and keyboard navigation keep working.

3. How can I get the chart’s labels, values and colors?

Labels and values. When a chart series gets its data through the standard data source (data.providing), the platform creates a page attribute named <ChartElementName>_SeriesData. For example, a chart element named MyDoughnut gets MyDoughnut_SeriesData. The attribute holds one array per series, and each item looks like this:

{
  grouping:    { value, displayValue }, // displayValue is the slice label
  aggregation: { value }                // value is the slice value
}

 

Please keep in mind:

  • The platform generates this attribute and it isn’t part of the documented API, so it may change in future versions.
  • It’s created only when the chart element has no explicit seriesData binding.
  • It’s filled asynchronously, so await it. It holds empty arrays until the data has loaded.

Colors. No API returns the colors the chart draws. Doughnut slices take colors from the built-in palette by slice index, starting again after the last color:

#0058EF, #F9307F, #08857E, #F86700, #4F43C2, #20A959, #009DE3, #FF4013, #B87CCF, #22AC14,
#247EE5, #FF602E, #9641A9, #0B6A32, #E00022, #1566B9, #BE1B5A, #7848EE, #0D2E4E

 

A legend that uses this list matches the chart today. The palette is an internal detail, though, so check the legend after upgrades.

Order. If the chart has a sort order (seriesOrder), sort your legend items the same way before assigning colors. Otherwise the colors won’t match the slices.

4. Is there a supported API to get the chart instance?

No. @creatio-devkit/common has no API that returns a page element’s component or the underlying Chart.js instance. The chart widget exposes only its configuration inputs, and clicks on the chart are handled inside the widget without reaching the page.

Reading the Chart.js instance from the component or the DOM depends on internal details, and we don’t recommend it. Chart.getChart(canvas) usually doesn’t work from custom code anyway. Custom code loads its own copy of Chart.js, which doesn’t know about the chart the widget created.

Recommended approach

Add a legend element under the chart and leave the chart widget as it is. There are three options, from simplest to most flexible.

Option 1. Text legend with a label (no custom component)

Add a crt.Label under the chart and fill it from a handler:

viewConfigDiff: /**SCHEMA_VIEW_CONFIG_DIFF*/[
  {
    "operation": "insert",
    "name": "MyDoughnutLegend",
    "values": {
      "type": "crt.Label",
      "caption": "$MyDoughnutLegendText",
      "labelType": "body",
      "visible": true
    },
    "parentName": "<container that holds MyDoughnut>",
    "propertyName": "items",
    "index": 1
  }
]/**SCHEMA_VIEW_CONFIG_DIFF*/,
viewModelConfigDiff: /**SCHEMA_VIEW_MODEL_CONFIG_DIFF*/[
  {
    "operation": "merge",
    "path": ["attributes"],
    "values": {
      "MyDoughnutLegendText": {}
    }
  }
]/**SCHEMA_VIEW_MODEL_CONFIG_DIFF*/,
handlers: /**SCHEMA_HANDLERS*/[
  {
    request: "crt.HandleViewModelAttributeChangeRequest",
    handler: async (request, next) => {
      if (request.attributeName === "MyDoughnut_SeriesData") {
        const seriesData = await request.$context.MyDoughnut_SeriesData;
        const items = seriesData?.[0] ?? [];
        request.$context.MyDoughnutLegendText = items
          .map(item => `${item.grouping.displayValue}: ${item.aggregation.value}`)
          .join("  |  ");
      }
      return next?.handle(request);
    }
  }
]/**SCHEMA_HANDLERS*/,

 

This option can’t show colored markers. Please check on your Creatio version that the change request fires for the generated attribute.

Option 2. Legend with colored markers (custom view element)

Create a small Angular component in a remote module (see “Develop a custom UI component using remote module” on Creatio Academy):

import { Component, Input, ViewEncapsulation } from '@angular/core';
import { CrtInput, CrtViewElement } from '@creatio-devkit/common';

const PALETTE = [
  '#0058EF', '#F9307F', '#08857E', '#F86700', '#4F43C2', '#20A959', '#009DE3',
  '#FF4013', '#B87CCF', '#22AC14', '#247EE5', '#FF602E', '#9641A9', '#0B6A32',
  '#E00022', '#1566B9', '#BE1B5A', '#7848EE', '#0D2E4E'
];

interface LegendItem {
  label: string;
  value: unknown;
}

@Component({
  selector: 'usr-chart-legend',
  template: `
    <div class="usr-legend">
      <span *ngFor="let item of legend; let i = index" class="usr-legend-item">
        <i [style.background]="color(i)"></i>{{ item.label }} ({{ item.value }})
      </span>
    </div>`,
  styles: [`
    .usr-legend { display: flex; flex-wrap: wrap; gap: 8px 16px; justify-content: center; }
    .usr-legend-item { display: inline-flex; align-items: center; }
    .usr-legend-item i { width: 10px; height: 10px; border-radius: 50%; margin-right: 6px; }
  `],
  encapsulation: ViewEncapsulation.Emulated
})
@CrtViewElement({
  selector: 'usr-chart-legend',
  type: 'usr.ChartLegend'
})
export class UsrChartLegendComponent {
  public legend: LegendItem[] = [];

  @Input()
  @CrtInput()
  public set items(value: any) {
    Promise.resolve(value).then(data => {
      this.legend = (data?.[0] ?? []).map((item: any) => ({
        label: item.grouping?.displayValue,
        value: item.aggregation?.value
      }));
    });
  }

  public color(index: number): string {
    return PALETTE[index % PALETTE.length];
  }
}

 

Register the component in the remote module the standard way. Then place it under the chart on the Freedom UI page:

{
  "operation": "insert",
  "name": "MyDoughnutLegend",
  "values": {
    "type": "usr.ChartLegend",
    "items": "$MyDoughnut_SeriesData"
  },
  "parentName": "<container that holds MyDoughnut>",
  "propertyName": "items",
  "index": 1
}

 

Option 3. Load the legend data yourself (fully supported API)

If you don’t want to depend on the generated _SeriesData attribute, load the same aggregated data with sdk.Model. Pass the result to the label from Option 1 or the component from Option 2:

const model = await sdk.Model.create("Account");
const rows = await model.load({
  attributes: [
    { name: "Industry", path: "Industry" },
    {
      name: "Count",
      path: "Id",
      type: "function",
      functionConfig: {
        type: "aggregation",
        aggregation: "Count",
        aggregationEval: "all"
      }
    }
  ],
  parameters: [
    /* the same filters the chart uses */
  ]
});

 

Use the same grouping column, filters and sort order as the chart so the legend rows match the slices.

Limitations

  • A custom legend doesn’t react to the chart’s interactive state, such as a hovered or drilled-down slice.
  • The color palette and the <ChartElementName>_SeriesData attribute are internal details that may change in future versions. Please check the legend after upgrades.

Registering the idea

We agree that a built-in legend for pie and doughnut charts would be useful, and adding one needs a platform change. Please send this idea to support@creatio.com so it’s registered with the R&D team and considered for the product roadmap. Including your use case, such as “legend below the doughnut chart with series colors and labels”, will help us prioritize it.

Show all comments