Build and manage portal charts

Build and manage portal charts

Use the Chart component to build KPI dashboards for clients, candidates and vendors. A chart can read a direct JSON dataset, run aggregate SOQL or call a custom Apex data provider. The portal builder can preview the chart with live Salesforce data or safe sample data before the page is published.

Add Chart from the Interactions section of the portal builder, select the component on the canvas and configure it in the properties panel.

The chart designer (version 11)

Charts no longer need to be configured trait by trait. Dropping a Chart block, or clicking the cog on an existing chart, opens the chart designer: a guided query builder that generates the aggregate SOQL, a Test query button that shows the labels and values returned, an Appearance tab and a live preview. The result is written back as the attributes documented below, so everything here still applies. Charts can also be placed as sized widgets in a Dashboard.

  1. Set Builder Preview to Sample data while designing the page.
  2. Choose the chart Type, height, colours, legend and axes.
  3. Choose a Data Source and configure Dataset, SOQL or Custom Data Provider.
  4. Enter Dataset Labels to name the series.
  5. Change Builder Preview to Live data to validate the Salesforce result.
  6. Test the published page as the intended guest or authenticated portal user.
  7. Optionally set Auto-refresh Seconds for a live dashboard.

Preview settings only affect the builder. A published portal always uses the configured data source and never substitutes sample data.

Choose a chart type

Type Best use Data notes
Bar Compare categories or periods Supports multiple and stacked datasets.
Horizontal Bar Compare categories with long labels Supports multiple and stacked datasets.
Line Trends over ordered periods Enable Fill Chart Area for an area-style chart.
Doughnut Part-to-whole composition Normally use one dataset.
Pie Part-to-whole composition Normally use one dataset.
Polar Area Compare values by angle and area Normally use one dataset.
Radar Compare several measures across datasets Use the same category order for each dataset.
Scatter Show the relationship between x and y values Use direct Dataset or a Custom Data Provider with { "x": 1, "y": 2 } points.
Bubble Compare x, y and magnitude Use direct Dataset or a Custom Data Provider with { "x": 1, "y": 2, "r": 8 } points.

The built-in SOQL provider returns a category label and one value, so it is most useful for bar, horizontal bar, line, doughnut, pie, polar area and radar charts.

Preview charts in the builder

Use Builder Preview to control data shown only on the builder canvas:

Option Behaviour
Auto: live, then sample Attempts the configured source. If it is missing, fails or returns no rows, the chart displays sample data with a warning. This is the default and preserves existing charts.
Live data Uses the selected Dataset, SOQL or Custom Data Provider. Errors and no-data states are shown without a sample fallback.
Sample data Does not call the live provider. It uses Preview Dataset when supplied, otherwise it creates type-compatible sample data.
Off Replaces the chart with a preview-disabled placeholder in the builder.

The canvas displays a Live data or Sample data badge, making it clear which source is being previewed. Auto mode also displays the live error when it falls back to a sample.

Supply representative sample data

Enter valid chart Dataset JSON in Preview Dataset when the generated sample is not representative. For example:

[
    {
        "labels": ["Invited", "Applied", "Shortlisted", "Placed"],
        "detail": [240, 156, 48, 17]
    }
]

Preview Dataset is ignored on published pages.

Live preview runs in the builder user's Salesforce context. A query can succeed for an administrator but fail or return different results for a guest or portal user, so published-page testing remains required.

Select the data source

The Data Source setting makes source selection explicit:

Option Behaviour
Auto (compatible) Uses Custom Data Provider when populated, otherwise SOQL, otherwise Dataset. Use this for charts created before the source selector was introduced.
Dataset JSON Uses the JSON entered in Dataset.
SOQL Runs the query entered in SOQL through the built-in provider.
Custom Data Provider Instantiates the Apex class entered in Custom Data Provider.

Choose one explicit source for new charts. Values left in the other source fields are ignored until their source is selected.

Understand Dataset Labels and Dataset

These settings describe different chart concepts:

Setting Component attribute Purpose
Dataset Labels details-labels A JSON array containing one display name per data series. These names appear in the legend and tooltips.
Dataset details A JSON array of data series. Each series contains category labels in labels and corresponding values in detail.

For example, this chart has three categories and two datasets:

Categories:       Jan      Feb      Mar
Applications:     120      135      148
Placements:        34       41       46

Dataset Labels:

["Applications", "Placements"]

Dataset:

[
    {
        "labels": ["Jan", "Feb", "Mar"],
        "detail": [120, 135, 148]
    },
    {
        "labels": ["Jan", "Feb", "Mar"],
        "detail": [34, 41, 46]
    }
]

The first Dataset Label names the first Dataset object, and so on. Each detail array must contain the same number of items as its own labels array.

The component builds the union of category labels and aligns each series by label. This means the following is valid and displays a gap for a category that is absent from a series:

[
    { "labels": ["Jan", "Feb"], "detail": [10, 20] },
    { "labels": ["Feb", "Mar"], "detail": [4, 8] }
]

Dataset and Dataset Labels must be valid JSON with double-quoted strings. JavaScript-style values such as ['Applications'] are not valid JSON.

Set custom dataset colours

The selected Color Palette is applied automatically. A direct dataset can override its colours:

[
    {
        "label": "Applications",
        "labels": ["Jan", "Feb", "Mar"],
        "detail": [120, 135, 148],
        "backgroundColor": "#D9A6C2",
        "borderColor": "#762F3D"
    }
]

bgColor remains supported for custom Apex providers and older datasets. Pie, doughnut and polar area charts accept an array of colours to style individual segments.

Configure a chart with SOQL

The SOQL source passes an aggregate query to the built-in chart provider and returns one dataset.

A chart query must:

For an opportunity pipeline chart, set Dataset Labels to:

["Pipeline value"]

Set SOQL to:

SELECT StageName label, SUM(Amount) value
FROM Opportunity
WHERE IsClosed = false
WITH SECURITY_ENFORCED
GROUP BY StageName
ORDER BY SUM(Amount) DESC
LIMIT 10

Use Record ID safely

The special :recordId bind is populated from the chart's Record ID setting on the server. The default is {{contactUser.Id}}, which normally resolves to the logged-in portal contact.

This example counts the contact's cases by status:

SELECT Status label, COUNT(Id) value
FROM Case
WHERE ContactId = :recordId
WITH SECURITY_ENFORCED
GROUP BY Status
ORDER BY COUNT(Id) DESC
LIMIT 20

Keep :recordId unquoted. The value is validated as a Salesforce ID and supplied as a query bind rather than inserted into the query text. An invalid Record ID is rejected.

SOQL security

The component validates the label alias, value alias and final LIMIT clause. It does not automatically add field-security enforcement. Include WITH SECURITY_ENFORCED and test object and field access as the intended portal user.

WITH SECURITY_ENFORCED checks object and field access, but does not apply record sharing. Add explicit filters that restrict results to the intended user, contact, account or record context.

Configure a Custom Data Provider

Use a Custom Data Provider for multiple datasets, several queries, missing-period handling, business calculations or x/y point data.

The component instantiates the class, passes the resolved Record ID to init, and calls getData. The class must have a no-argument constructor and extend b3p.ChartDataProvider. Invalid or unrelated class types are rejected before execution.

This provider returns two series for a contact's cases:

global with sharing class PortalCasePriorityChartProvider
    extends b3p.ChartDataProvider {

    private Id contactId;

    global override void init(Object initParameter) {
        if (initParameter != null && String.isNotBlank(String.valueOf(initParameter))) {
            contactId = (Id) String.valueOf(initParameter);
        }
    }

    global override List<b3p.ChartDataProvider.ChartData> getData() {
        List<String> categories = new List<String>();
        Map<String, Decimal> highByStatus = new Map<String, Decimal>();
        Map<String, Decimal> otherByStatus = new Map<String, Decimal>();

        for (AggregateResult row : [
            SELECT Status statusLabel, Priority priorityLabel, COUNT(Id) itemCount
            FROM Case
            WHERE ContactId = :contactId
            WITH SECURITY_ENFORCED
            GROUP BY Status, Priority
            LIMIT 100
        ]) {
            String status = (String) row.get('statusLabel');
            String priority = (String) row.get('priorityLabel');
            Decimal countValue = Decimal.valueOf(String.valueOf(row.get('itemCount')));

            if (!categories.contains(status)) categories.add(status);

            if (priority == 'High') {
                highByStatus.put(status, countValue);
            } else {
                Decimal currentValue = otherByStatus.containsKey(status)
                    ? otherByStatus.get(status)
                    : 0;
                otherByStatus.put(status, currentValue + countValue);
            }
        }

        b3p.ChartDataProvider.ChartData high = new b3p.ChartDataProvider.ChartData();
        high.labels = categories;
        high.detail = valuesFor(categories, highByStatus);

        b3p.ChartDataProvider.ChartData other = new b3p.ChartDataProvider.ChartData();
        other.labels = categories;
        other.detail = valuesFor(categories, otherByStatus);

        return new List<b3p.ChartDataProvider.ChartData>{ high, other };
    }

    private static List<Object> valuesFor(
        List<String> categories,
        Map<String, Decimal> valuesByCategory
    ) {
        List<Object> values = new List<Object>();
        for (String category : categories) {
            values.add(valuesByCategory.containsKey(category) ? valuesByCategory.get(category) : 0);
        }
        return values;
    }
}

Configure the chart with:

Setting Value
Data Source Custom Data Provider
Type Bar
Dataset Labels ["High priority", "Other priorities"]
Record ID {{contactUser.Id}}
Custom Data Provider PortalCasePriorityChartProvider

Use a namespace-qualified class name when required, such as customerNamespace.PortalCasePriorityChartProvider.

Each returned ChartData item represents one dataset:

Field Type Required Purpose
labels List<String> Yes for category charts Category labels corresponding to detail.
detail List<Object> Yes Numeric values, scatter points or bubble points.
bgColor String No Dataset background colour.

Declare an intentional sharing model and enforce object and field access in custom providers. A provider can execute for guest portal traffic and must not assume an authenticated internal Salesforce user.

Appearance and dashboard options

Setting Component attribute Behaviour
Theme theme-type Applies the selected portal theme.
Title title Displays a heading above the chart.
Show Legend show-legend Shows or hides dataset names.
Legend Position legend-position Places the legend at the top, bottom, left or right.
Color Palette color-palette Applies one of the standard accessible palette choices.
Fill Chart Area fill Fills line and radar datasets.
Stack Datasets stacked Stacks bar or horizontal bar datasets.
Begin Axis at Zero begin-at-zero Starts numeric axes at zero.
X-axis Title x-axis-title Adds an x-axis label to cartesian charts.
Y-axis Title y-axis-title Adds a y-axis label to cartesian charts.
Chart Height chart-height Sets a CSS height such as 320px or 24rem.
Value Format value-format Formats numeric axes and tooltips as number, compact number, currency or percentage.
Currency Code currency-code ISO currency code used when Value Format is Currency, such as GBP, EUR or USD.
Auto-refresh Seconds refresh-interval Reloads live portal data on an interval. Use 0 to disable or a value of at least 15 seconds. Builder previews do not auto-refresh.
No Data Message empty-message Replaces the default no-data message.

Percentage formatting expects a ratio. For example, 0.42 displays as 42%.

Component markup examples

SOQL chart:

<x-chart-builder
    source-type="soql"
    type="bar"
    title="Cases by status"
    theme-type="emerald"
    show-legend="true"
    legend-position="top"
    color-palette="colorsafe"
    value-format="number"
    chart-height="360px"
    preview-mode="auto"
    details-labels='["Cases"]'
    record-id="{{contactUser.Id}}"
    soql="SELECT Status label, COUNT(Id) value FROM Case WHERE ContactId = :recordId WITH SECURITY_ENFORCED GROUP BY Status ORDER BY COUNT(Id) DESC LIMIT 20">
</x-chart-builder>

Direct multi-series chart:

<x-chart-builder
    source-type="dataset"
    type="line"
    title="Applications and placements"
    theme-type="light"
    legend-position="bottom"
    preview-mode="sample"
    details-labels='["Applications", "Placements"]'
    details='[{"labels":["Jan","Feb","Mar"],"detail":[120,135,148]},{"labels":["Jan","Feb","Mar"],"detail":[34,41,46]}]'>
</x-chart-builder>

Compatibility with existing charts

Existing x-chart-builder markup remains valid. When Source Type is absent or set to Auto, the component uses Custom Data Provider, then SOQL, then Dataset based on which fields are populated. Existing details, details-labels, soql, handler, record-id, type, palette, fill and appearance attributes continue to work.

Existing charts benefit automatically from refreshed category alignment, request race protection, corrected boolean handling and safer Record ID binding. Review charts that contain more than one populated source field and select an explicit Data Source to remove ambiguity.

Troubleshooting

Symptom Check
Sample data appears unexpectedly Auto preview could not load the configured source. Read the warning on the chart or select Live data to see the source error without fallback.
Query must contains "label" alias Add the exact alias label after the grouping field or expression.
Query must contains "value" alias Add the exact alias value after the aggregate expression.
Query must contains "LIMIT" statement End the query with a numeric limit, such as LIMIT 20.
Record ID is invalid Ensure Record ID resolves to a 15-character or 18-character Salesforce ID and keep :recordId unquoted.
Dataset JSON error Use a JSON array, double-quote strings and ensure every dataset has a detail array.
Labels and values do not align Make each dataset's labels and detail arrays the same length.
No legend label Supply one Dataset Label per series, or add a label property to direct Dataset objects.
Apex provider cannot be created Check the class name, namespace, visibility, no-argument constructor and inheritance from b3p.ChartDataProvider.
Live preview differs from the portal Test sharing, field permissions, merge values and filters using the intended portal user.
Auto-refresh does not run Use a value of 15 seconds or more. Refresh is disabled in the builder and for lower values.

Issues addressed by the chart refactor

The revised chart component corrects the following previous behaviours: