grafana / scenes

Build Grafana dashboards directly in your Grafana app plugins.
https://grafana.com/developers/scenes
Apache License 2.0
141 stars 21 forks source link

How to handle duplicates in variables/dropdowns #646

Closed ptrkkr closed 7 months ago

ptrkkr commented 8 months ago

Hi Team!

Following problem we have We want to have a dropdown, which shows a list of string values, which represent a column of a database table for example. When clicking on the dropdown entry it should show a table based on the selected value. The problem is if there are duplicated string values in the dropdown, then we wont be able to select the right data based on these values.

We would expect to be able (like in 'normal' frontend frameworks) to put more complex objects into a dropdown and then use the id of this complex object to query for new data.

Questions

Thx in advance!

ptrkkr commented 8 months ago

I have seen this question here and @torkelo said that there a value and text representations of variables. This would be great! But i don't know how it can be set. Does anyone have some experience with that?

ptrkkr commented 7 months ago

I have found a way to do it :+1: For everyone interested, here is an example using the infinity data source:

return new QueryVariable({
    name: 'host',
    label: 'Host',
    datasource: ANY_DATASOURCE,
    query: {
      refId: 'host',
      infinityQuery: {
        parser: 'backend',
        refId: 'hostVariable', // this is a necessary field
        root_selector: "data.(name & ';;' & hostId)", // selects the data you want from the json using JSONata
        url: `${HOST_ENDPOINT}`,
        url_options: {
          method: 'GET',
        },
      },
      queryType: 'infinity',
    },
    sort: VariableSort.alphabeticalAsc,
    placeholder: 'No Host selected',
    regex: '(?<text>.*);;(?<value>.*)', // most important part! Here we define what our display text and value is. The regex groups must be 'text' and 'value' to work
  });
}

You can see the regex documentation (example) for dashboards here. After you have defined the two groups in the regex, Grafana automatically uses the value for queries and the text for dropdowns or other representations visible to the user.