Enterprise Open source Grafana Cloud

Custom code

You can use custom code 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 and when Element Value Changed occurs.

Parameters

ParameterDescriptionInitial, UpdateChange valueShowIf, DisableIf, GET options
context.elementCurrent elementYES
context.panel.dataResult set of panel queries.YESYESYES (For Get Options)
context.panel.elementsForm elements.YESYESYES
context.panel.initialParsed values from the initial request.YESYES
context.panel.initialRequest()Performs an initial request to reload the panel.YESYES
context.panel.optionsPanel’s options.YESYES
context.panel.onOptionsChange({})Modifies a handler to refresh the panel.YESYES
context.panel.onChangeElements([])Updates elements in the local state. Change elements. Accepts an array of new elements.YESYES
context.panel.patchFormValue({})Update the value of the elements. Accepts an object.YESYES
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.YESYES
context.panel.formValue()Contains a current form value as object.YESYES
context.panel.responseRequest’s response.YES
context.panel.setInitial({})Specifies initial values for a custom initial request to highlight modified values and requests a user’s confirmation.YES
context.panel.enableSubmit()Enable Submit buttonYESYES
context.panel.disableSubmit()Disable Submit buttonYESYES
context.panel.enableReset()Enable Reset buttonYES
context.panel.disableReset()Disable Reset buttonYES
context.panel.enableSaveDefault()Enable Save Default buttonYES
context.panel.disableSaveDefault()Disable Save Default buttonYES
context.panel.setError('Message')Displays an error on panel.YES
context.panel.sectionsUtils.add(section)Add a new Section. Added in v4.9.0.YESYES
context.panel.sectionsUtils.update(sections)Change Sections. Added in v4.9.0.YESYES
context.panel.sectionsUtils.remove(id)Remove Section. Added in v4.9.0.YESYES
context.panel.sectionsUtils.assign(id, elements)Assign elements to Section. Added in v4.9.0.YESYES
context.panel.sectionsUtils.unassign(elements)Unassign elements from Section. Added in v4.9.0.YESYES
context.panel.sectionsUtils.get(id)Get Section by id. Return Section with elements assign to section. Added in v4.9.0.YESYES
context.panel.sectionsUtils.getAll()Get All Sections. Return Sections with elements assign to each section. Added in v4.9.0.YESYES
context.panel.sectionsUtils.collapse(id)Collapse Section. Updated in v4.9.0.YESYES
context.panel.sectionsUtils.expand(id)Expand Section. Updated in v4.9.0.YESYES
context.panel.sectionsUtils.toggle(id)Toggle (Collapse/Expand) Section. Updated in v4.9.0.YESYES
context.panel.sectionsUtils.expandedStateReturn Expand/Collapse State for Sections. Updated in v4.9.0.YESYES
context.grafana.locationServiceGrafana’s locationService function to work with the browser’s location and history.YESYES
context.grafana.backendServiceGrafana’s backendService used to communicate to a remote backend such as the Grafana backend, a datasource etc.YES
context.grafana.notifyError(['Header', 'Message'])Displays an error.YESYES
context.grafana.notifySuccess(['Header', 'Message'])Displays a success notification.YESYES
context.grafana.notifyWarning(['Header', 'Message'])Displays a warning.YESYES
context.grafana.eventBusPublish and subscribe to application events.YESYES
context.grafana.templateServiceGrafana’s templateService function that provides access to variables and enables the update of a time range.YESYES
context.grafana.refresh()Function to refresh dashboard panels using application events.YESYES
context.utils.fileToBase64(file)Convert to base64 formatYES
context.utils.toDataQueryResponse(data)Parse the results from /api/ds/query into a DataQueryResponseYESYES

Inspect parameters

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

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

Refresh the dashboard after an update request or show a warning

The following example shows how to refresh the dashboard after a successful update request or display an error notification if the request fails.

JavaScript
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 a variable after an update request to interact with other panels

The following example demonstrates how to update a dashboard variable with data from the response, enabling interaction with other panels.

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

Perform an initial request after an update request or show an error

The following example shows how to trigger an initial request to reload the panel after a successful update or display an error notification if the request fails.

JavaScript
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 an initial request only on dashboard load

The following example demonstrates how to fetch and populate form elements only when the dashboard first loads, avoiding unnecessary requests on subsequent interactions.

JavaScript
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.onChangeElements(
      context.panel.elements.map((element) => ({
        ...element,
        value: json[element.id],
      }))
    );
  }
};

return getValues();

Clear element values after clicking the Submit or Reset button

The following example shows how to reset or modify form element values programmatically.

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

Note

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

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

Update the local state in Data Manipulation panel 3.1.0

The following example demonstrates how to update element values in the local state without refreshing the entire panel.

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

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

Simplified form elements patchFormValue helper

Before version 4.4.0, to update a form element value, you had to use context.panel.elements.map(). In version 4.4.0, a new function was added to simplify that approach. It accepts an object with element IDs as keys and their new values.

Before 4.4.0 version:

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

The simplified version example:

JavaScript
// 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 form elements formValue helper

Before version 4.4.0, to get form element values, you had to use context.panel.elements.forEach(). In version 4.4.0, a new function was added to simplify that approach. It returns an object with element IDs as keys.

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 }