Skip to main content

Custom Code

Custom code allows you to access the panel's options, REST API responses, form elements, and various Grafana services.

Custom code is executed after the Initial and Update requests, when Element Value Changed.

Parameters

ParameterDescriptionInitial, UpdateChange ValueShowIf, DisableIf, Get Options
context.elementCurrent element✔️
context.panel.dataResult set of panel queries.✔️✔️✔️ (For Get Options)
context.panel.elementsForm elements.✔️✔️✔️
context.panel.initialParsed values from the initial request.✔️✔️
context.panel.initialRequest()Performs an initial request to reload the panel.✔️✔️
context.panel.onChange()Updates elements in the local state. Added in v3.1.0.✔️✔️
context.panel.optionsPanel's options.✔️✔️
context.panel.onOptionsChange()Modifies a handler to refresh the panel.✔️✔️
context.panel.onChangeElements([])Change elements. Accepts an array of new elements.✔️✔️
context.panel.patchFormValue({})Update the value of the elements. Accepts an object.✔️✔️
context.panel.setFormValue({})Update the value of the elements. Accepts an object. If value is not passed to the element, the value should be used from initial or cleared.✔️✔️
context.panel.formValue()Contains a current form value as object.✔️✔️
context.panel.responseRequest's response.✔️
context.panel.setInitial({})Specifies initial values for a custom initial request to highlight modified values and requests a user's confirmation.✔️
context.panel.enableSubmit()Enable Submit button✔️✔️
context.panel.disableSubmit()Disable Submit button✔️✔️
context.panel.enableReset()Enable Reset button✔️
context.panel.disableReset()Disable Reset button✔️
context.panel.enableSaveDefault()Enable Save Default button✔️
context.panel.disableSaveDefault()Disable Save Default button✔️
context.panel.setError('Message')Displays an error on panel.✔️
context.panel.collapseSection(id)Collapse Section. Added in v4.0.0.✔️✔️
context.panel.expandSection(id)Expand Section. Added in v4.0.0.✔️✔️
context.panel.toggleSection(id)Toggle (Collapse/Expand) Section. Added in v4.0.0.✔️✔️
context.panel.sectionsExpandedStateExpand/Collapse State for Sections. Added in v4.0.0.✔️✔️
context.grafana.locationServiceGrafana's locationService function to work with the browser's location and history.✔️✔️
context.grafana.backendServiceGrafana's backendService used to communicate to a remote backend such as the Grafana backend, a datasource etc.✔️
context.grafana.notifyError(['Header', 'Message'])Displays an error.✔️✔️
context.grafana.notifySuccess(['Header', 'Message'])Displays a success notification.✔️✔️
context.grafana.notifyWarning(['Header', 'Message'])Displays a warning.✔️✔️
context.grafana.eventBusPublish and subscribe to application events.✔️✔️
context.grafana.templateServiceGrafana's templateService function that provides access to variables and enables the update of a time range.✔️✔️
context.grafana.refresh()Function to refresh dashboard panels using application events.✔️✔️
context.grafana.replaceVariables()Function to interpolate variables.✔️

To find out the current parameters, you can log them in the browser's console:

console.log(
context.panel.options,
context.panel.data,
context.panel.response,
context.panel.elements,
context.grafana.locationService,
context.grafana.templateService
);

Refresh Dashboard after update request or show warning

if (context.panel.response && context.panel.response.ok) {
context.grafana.notifySuccess(["Update", "Values updated successfully."]);
context.grafana.refresh();
} else {
context.grafana.notifyError([
"Update",
`An error occurred updating values: ${context.panel.response.status}`,
]);
}

Update variable after update request to interact with other panels

if (context.panel.response && context.panel.response.ok) {
context.panel.response.json().then((resp) => {
context.grafana.locationService.partial({ "var-name": resp["name"] }, true);
});
}

Perform Initial Request after update request or show error

if (context.panel.response && context.panel.response.ok) {
context.grafana.notifySuccess(["Update", "Values updated successfully."]);
context.panel.initialRequest();
} else {
context.grafana.notifyError([
"Error",
`An error occurred updating values: ${context.panel.response.status}`,
]);
}

Perform initial request only on dashboard load

const getValues = async () => {
/**
* Check if all values are empty
*/
const isFirstLoad = context.panel.elements.every((element) => !element.value);

if (isFirstLoad) {
/**
* Get Data
*/
const response = await fetch();
const json = await response.json();

/**
* Update initial element values
*/
context.panel.onChange(
context.panel.elements.map((element) => ({
...element,
value: json[element.id],
}))
);
}
};

return getValues();

Clear elements' values after click on the Submit or Reset button

context.panel.onOptionsChange({
...context.panel.options,
elements: context.panel.options.elements.map((element) => {
return element.id === "name" ? { ...element, value: "test" } : element;
}),
});
Refresh panel

The context.panel.onOptionsChange() handler calls refresh panel.

The context.panel.onOptionsChange() handler is required to update the panel.

Update local state in Data Manipulation panel 3.1.0

context.panel.onChange(
elements.map((element) => {
return element.id === "name" ? { ...element, value: "test" } : element;
})
);

The context.panel.onChange() function is required to update the element values in the local state.

Simplified the Form Elements patchFormValue helper

Before version 4.4.0, in order to update a form element value, a user had to use context.panel.elements.map(). In the 4.4.0, we added a new function to simplify that approach. It has an object's key as an inpit parameter and a new value.

Before 4.4.0 version:

context.panel.onChangeElements(
context.panel.elements.map((element) =>
element.id === "name" ? { ...element, value: "Alex" } : element
)
);

The simplified version example:

// only passed elements should be updated, the rest stay the same
context.panel.patchFormValue({ name: "Alex" });
// name and isAdmin
context.panel.patchFormValue({ name: "Alex", isAdmin: true });

Simplified the Form Elements formValue helper

Before version 4.4.0, in order to get a form element value, a user had to use context.panel.elements.forEach(). In the 4.4.0, we added a new function to simplify that approach. It has an object's key as an inpit parameter.

Before 4.4.0 version:

const payload = {};

context.panel.elements.forEach((element) => {
payload[element.id] = element.value;
});

// payload = { name: 'Alex', isAdmin: true }

The simplified version example:

context.panel.formValue // { name: 'Alex', isAdmin: true }