The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Pass label_field for parameter card dropdown sources (#74597)
Alexander Polyankin1c4cec154075
diff --git a/.loki/reference/chrome_laptop_App_Embed_PublicOrEmbeddedDashboardView_filters_Dark_Theme_Parameter_Search_With_Value.png b/.loki/reference/chrome_laptop_App_Embed_PublicOrEmbeddedDashboardView_filters_Dark_Theme_Parameter_Search_With_Value.pngindex 426ffef3378..826b967c9ef 100644Binary files a/.loki/reference/chrome_laptop_App_Embed_PublicOrEmbeddedDashboardView_filters_Dark_Theme_Parameter_Search_With_Value.png and b/.loki/reference/chrome_laptop_App_Embed_PublicOrEmbeddedDashboardView_filters_Dark_Theme_Parameter_Search_With_Value.png differdiff --git a/.loki/reference/chrome_laptop_App_Embed_PublicOrEmbeddedDashboardView_filters_Light_Theme_Parameter_Search_With_Value.png b/.loki/reference/chrome_laptop_App_Embed_PublicOrEmbeddedDashboardView_filters_Light_Theme_Parameter_Search_With_Value.pngindex 6ae789eef62..197d368801a 100644Binary files a/.loki/reference/chrome_laptop_App_Embed_PublicOrEmbeddedDashboardView_filters_Light_Theme_Parameter_Search_With_Value.png and b/.loki/reference/chrome_laptop_App_Embed_PublicOrEmbeddedDashboardView_filters_Light_Theme_Parameter_Search_With_Value.png differdiff --git a/e2e/support/helpers/e2e-filter-helpers.js b/e2e/support/helpers/e2e-filter-helpers.jsindex b719ff605f4..4162fa31a25 100644--- a/e2e/support/helpers/e2e-filter-helpers.js+++ b/e2e/support/helpers/e2e-filter-helpers.js@@ -10,7 +10,7 @@ export function setSearchBoxFilterType() {cy.findByText("Search box").click();}-export function setFilterQuestionSource({ question, field }) {+export function setFilterQuestionSource({ question, field, labelField }) {cy.findByText("Edit").click();modal().within(() => {@@ -28,6 +28,18 @@ export function setFilterQuestionSource({ question, field }) {cy.findByText(field).click();});+ if (labelField) {+ cy.log("the label selector defaults to None until a column is chosen");+ modal().within(() => {+ cy.findByText("Column to supply the labels").should("be.visible");+ cy.findByText("None").click();+ });++ popover().within(() => {+ cy.findByText(labelField).click();+ });+ }+modal().within(() => {cy.button("Done").click();});diff --git a/e2e/test/scenarios/dashboard-filters/dashboard-filters-source.cy.spec.js b/e2e/test/scenarios/dashboard-filters/dashboard-filters-source.cy.spec.jsindex c530d546627..445009a9202 100644--- a/e2e/test/scenarios/dashboard-filters/dashboard-filters-source.cy.spec.js+++ b/e2e/test/scenarios/dashboard-filters/dashboard-filters-source.cy.spec.js@@ -118,6 +118,89 @@ describe("scenarios > dashboard > filters", { tags: "@slow" }, () => {});});+ describe("question source with custom labels", () => {+ const stringLabelSource = {+ name: "String label source",+ native: {+ query:+ "SELECT DISTINCT CATEGORY, CONCAT(CATEGORY, ' Label') AS LABEL " ++ "FROM PRODUCTS WHERE CATEGORY != 'Doohickey'",+ },+ };++ const numberLabelSource = {+ name: "Number label source",+ native: {+ query: "SELECT ID, TITLE FROM PRODUCTS ORDER BY ID ASC LIMIT 5",+ },+ };++ it("should remap a string value to a string label (string/string)", () => {+ H.createNativeQuestion(stringLabelSource, { wrapId: true });+ H.createQuestionAndDashboard({+ questionDetails: targetQuestion,+ }).then(({ body: { dashboard_id } }) => {+ H.visitDashboard(dashboard_id);+ });++ H.editDashboard();+ H.setFilter("Text or Category", "Is");+ mapFilterToQuestion();+ H.setFilterQuestionSource({+ question: "String label source",+ field: "CATEGORY",+ labelField: "LABEL",+ });+ H.saveDashboard();++ cy.log("the dropdown shows the labels instead of the raw values");+ H.filterWidget().click();+ H.popover().within(() => {+ cy.findByText("Gadget Label").should("be.visible");+ cy.findByText("Gizmo Label").should("be.visible");+ cy.findByText("Gizmo").should("not.exist");+ cy.findByText("Gizmo Label").click();+ cy.button("Add filter").click();+ });++ cy.log("the selected value is shown remapped to its label");+ H.filterWidget().findByText("Gizmo Label").should("be.visible");+ });++ it("should remap a number value to a string label (number/string)", () => {+ H.createNativeQuestion(numberLabelSource, { wrapId: true });+ H.createQuestionAndDashboard({+ questionDetails: targetQuestion,+ }).then(({ body: { dashboard_id } }) => {+ H.visitDashboard(dashboard_id);+ });++ H.editDashboard();+ H.setFilter("Number", "Equal to", "Number");++ mapFilterToQuestion("Rating");+ H.setFilterQuestionSource({+ question: "Number label source",+ field: "ID",+ labelField: "TITLE",+ });+ H.saveDashboard();++ cy.log(+ "the dropdown shows the product titles instead of the numeric ids",+ );+ H.filterWidget().click();+ H.popover().within(() => {+ cy.findByText("Rustic Paper Wallet").should("be.visible");+ cy.findByText("Rustic Paper Wallet").click();+ cy.button("Add filter").click();+ });++ cy.log("the selected value is shown remapped to its label");+ H.filterWidget().findByText("Rustic Paper Wallet").should("be.visible");+ });+ });+describe("native question source", () => {it("should be able to use a native question source", () => {H.createNativeQuestion(nativeSourceQuestion, { wrapId: true });diff --git a/frontend/src/metabase-lib/v1/parameters/utils/parameter-source.ts b/frontend/src/metabase-lib/v1/parameters/utils/parameter-source.tsindex 134c8157f8a..336fbbe74b5 100644--- a/frontend/src/metabase-lib/v1/parameters/utils/parameter-source.ts+++ b/frontend/src/metabase-lib/v1/parameters/utils/parameter-source.ts@@ -1,4 +1,4 @@-import type Field from "metabase-lib/v1/metadata/Field";+import Field from "metabase-lib/v1/metadata/Field";import { isFuzzyOperator } from "metabase-lib/v1/operators/utils";import type {Parameter,@@ -38,6 +38,36 @@ export const getSourceConfig = (parameter: Parameter): ValuesSourceConfig => {return parameter.values_source_config ?? {};};+/**+ * Whether the parameter's selected values can be remapped to human-readable+ * labels. True when a connected field has a remapping, when a static list+ * includes [value, label] pairs, or when a card/question source configures a+ * label column.+ */+export const hasRemappedParameterValues = (+ parameter: Parameter | null | undefined,+ fields: Field[],+): boolean => {+ if (Field.remappedField(fields) != null) {+ return true;+ }++ if (parameter == null) {+ return false;+ }++ const sourceType = getSourceType(parameter);+ const sourceConfig = getSourceConfig(parameter);+ const sourceLabelField = sourceConfig.label_field;+ const sourceValues = sourceConfig.values ?? [];++ return (+ (sourceType === "static-list" &&+ sourceValues.some((value) => Array.isArray(value) && value.length > 1)) ||+ (sourceType === "card" && sourceLabelField != null)+ );+};+export const canUseCustomSource = (parameter: Parameter) => {const type = getParameterType(parameter);@@ -68,11 +98,11 @@ export const isValidSourceConfig = (export const getSourceConfigForType = (sourceType: ValuesSourceType,- { card_id, value_field, values }: ValuesSourceConfig,+ { card_id, value_field, label_field, values }: ValuesSourceConfig,): ValuesSourceConfig => {switch (sourceType) {case "card":- return { card_id, value_field };+ return { card_id, value_field, label_field };case "static-list":return { values };default:diff --git a/frontend/src/metabase-types/api/parameters.ts b/frontend/src/metabase-types/api/parameters.tsindex f6ba79d24d9..e301cfc6c64 100644--- a/frontend/src/metabase-types/api/parameters.ts+++ b/frontend/src/metabase-types/api/parameters.ts@@ -73,6 +73,7 @@ export interface ValuesSourceConfig {values?: string[] | ParameterValue[];card_id?: CardId;value_field?: FieldReference;+ label_field?: FieldReference;}export type VariableTarget = ["template-tag", string];diff --git a/frontend/src/metabase/hoc/Remapped.jsx b/frontend/src/metabase/hoc/Remapped.jsxindex 539d2afa626..e3b6bf2c77f 100644--- a/frontend/src/metabase/hoc/Remapped.jsx+++ b/frontend/src/metabase/hoc/Remapped.jsx@@ -28,48 +28,70 @@ export default (ComposedComponent) =>(ComposedComponent.displayName || ComposedComponent.name) +"]";+ state = { remapping: null };+UNSAFE_componentWillMount() {- if (this.props.column) {- this.props.fetchRemapping({- parameter: this.props.parameter,- value: this.props.value,- field: this.props.column,- cardId: this.props.cardId,- dashboardId: this.props.dashboardId,- uuid: this.props.uuid,- token: this.props.token,- });- }+ this.fetchRemapping(this.props);}+UNSAFE_componentWillReceiveProps(nextProps) {if (- nextProps.column &&- (this.props.value !== nextProps.value ||- this.props.column?.id !== nextProps.column.id ||- this.props.parameter?.id !== nextProps.parameter?.id ||- this.props.cardId !== nextProps.cardId ||- this.props.dashboardId !== nextProps.dashboardId ||- this.props.uuid !== nextProps.uuid ||- this.props.token !== nextProps.token)+ this.props.value !== nextProps.value ||+ this.props.column?.id !== nextProps.column?.id ||+ this.props.parameter?.id !== nextProps.parameter?.id ||+ this.props.cardId !== nextProps.cardId ||+ this.props.dashboardId !== nextProps.dashboardId ||+ this.props.uuid !== nextProps.uuid ||+ this.props.token !== nextProps.token) {- this.props.fetchRemapping({- parameter: nextProps.parameter,- value: nextProps.value,- field: this.props.column,- cardId: nextProps.cardId,- dashboardId: nextProps.dashboardId,- uuid: nextProps.uuid,- token: nextProps.token,- });+ this.setState({ remapping: null });+ this.fetchRemapping(nextProps);+ }+ }++ async fetchRemapping(props) {+ const result = await props.fetchRemapping({+ parameter: props.parameter,+ value: props.value,+ field: props.column,+ cardId: props.cardId,+ dashboardId: props.dashboardId,+ uuid: props.uuid,+ token: props.token,+ });++ const remapping = result?.payload;+ if (remapping != null && props.value === this.props.value) {+ this.setState({ remapping });}}+ getDisplayValue(field, value) {+ const fieldDisplayValue = field && field.remappedValue(value);+ if (fieldDisplayValue != null) {+ return fieldDisplayValue;+ }++ const [, remappedLabel] = this.state.remapping ?? [];+ if (remappedLabel != null) {+ return remappedLabel;+ }++ return null;+ }+render() {const { metadata, fetchRemapping, ...props } = this.props;- const field = props.column;- const displayValue = field && field.remappedValue(props.value);+ // Read the field from metadata so we pick up remappings stored+ // asynchronously by fetchRemapping (e.g. card/question label columns);+ // the column passed in props can be a stale instance.+ const field =+ (props.column?.id != null && metadata?.field(props.column.id)) ||+ props.column;+ const displayValue = this.getDisplayValue(field, props.value);const displayColumn =(displayValue != null && field && field.remappedField()) || null;+return (<ComposedComponent{...props}diff --git a/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.tsx b/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.tsxindex 0b4f0d610c2..d36abd1e386 100644--- a/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.tsx+++ b/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.tsx@@ -11,6 +11,7 @@ import {hasFields,isFieldFilterUiParameter,} from "metabase-lib/v1/parameters/utils/parameter-fields";+import { hasRemappedParameterValues } from "metabase-lib/v1/parameters/utils/parameter-source";import {isBooleanParameter,isDateParameter,@@ -53,19 +54,14 @@ function FormattedParameterValue({}const first = getValue(value);- const values = parameter?.values_source_config?.values;- const displayValue = values?.find(- (value) => getValue(value)?.toString() === first?.toString(),- );-- const label = !isBooleanParameter(parameter)- ? getLabel(displayValue)- : getBooleanLabel(first as boolean);+ const label = isBooleanParameter(parameter)+ ? getBooleanLabel(first as boolean)+ : undefined;const renderContent = () => {if (- isFieldFilterUiParameter(parameter) &&- hasFields(parameter) &&+ ((isFieldFilterUiParameter(parameter) && hasFields(parameter)) ||+ hasRemappedParameterValues(parameter, getFields(parameter))) &&!isDateParameter(parameter) &&!isTemporalUnitParameter(parameter)) {@@ -123,15 +119,6 @@ function getValue(return value?.toString();}-function getLabel(- value: boolean | string | ParameterValue | undefined,-): string | undefined {- if (Array.isArray(value)) {- return value[1];- }- return value?.toString();-}-function getBooleanLabel(value: boolean) {return value ? t`True` : t`False`;}diff --git a/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.unit.spec.tsx b/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.unit.spec.tsxindex b8c9f5791a0..6c858ad6b7c 100644--- a/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.unit.spec.tsx+++ b/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.unit.spec.tsx@@ -34,7 +34,7 @@ function setup({}describe("FormattedParameterValue", () => {- it("should render the custom label for a parameter value if it exists", () => {+ it("renders the raw value for a list source without connected fields (remapping is delegated to the field widget)", () => {setup({value: "A",parameter: createMockParameter({@@ -45,21 +45,10 @@ describe("FormattedParameterValue", () => {}),});- expect(screen.getByText("Custom Label")).toBeInTheDocument();- });-- it("should render the custom label for a parameter value if does not exist", () => {- setup({- value: "B",- parameter: createMockParameter({- values_source_type: "static-list",- values_source_config: {- values: [["A", "Custom Label"], ["B"]],- },- }),- });-- expect(screen.getByText("B")).toBeInTheDocument();+ // Without connected fields the raw value is shown; the [value, label] pair+ // is resolved by ParameterFieldWidgetValue through the remapping endpoint.+ expect(screen.getByText("A")).toBeInTheDocument();+ expect(screen.queryByText("Custom Label")).not.toBeInTheDocument();});it("should render the placeholder with truncation when there is no value", () => {diff --git a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.unit.spec.tsx b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.unit.spec.tsxindex 11429aea1ac..79d4ea2c4a2 100644--- a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.unit.spec.tsx+++ b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceModal.unit.spec.tsx@@ -252,6 +252,153 @@ describe("ValuesSourceModal", () => {});});+ it("should not show the label field selector until a value field is selected", async () => {+ await setup({+ parameter: createMockUiParameter({+ values_source_type: "card",+ values_source_config: {+ card_id: 1,+ },+ }),+ cards: [+ createMockCard({+ id: 1,+ name: "Products",+ result_metadata: [+ createMockField({+ id: 2,+ name: "category",+ display_name: "Category",+ base_type: "type/Text",+ effective_type: "type/Text",+ semantic_type: "type/Category",+ }),+ ],+ }),+ ],+ });++ expect(+ screen.getByText("Column to supply the values"),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("Column to supply the labels"),+ ).not.toBeInTheDocument();+ });++ it("should only offer text columns as the label field for remapping", async () => {+ const { onSubmit } = await setup({+ parameter: createMockUiParameter({+ values_source_type: "card",+ values_source_config: {+ card_id: 1,+ value_field: ["field", 2, null],+ // start with a label so we exercise selecting a different one+ label_field: ["field", 3, null],+ },+ }),+ cards: [+ createMockCard({+ id: 1,+ name: "Products",+ result_metadata: [+ createMockField({+ id: 1,+ name: "id",+ display_name: "ID",+ base_type: "type/BigInteger",+ effective_type: "type/BigInteger",+ semantic_type: "type/PK",+ }),+ createMockField({+ id: 2,+ name: "category",+ display_name: "Category",+ base_type: "type/Text",+ effective_type: "type/Text",+ semantic_type: "type/Category",+ }),+ createMockField({+ id: 3,+ name: "title",+ display_name: "Title",+ base_type: "type/Text",+ effective_type: "type/Text",+ semantic_type: "type/Title",+ }),+ ],+ }),+ ],+ });+ expect(+ screen.getByText("Column to supply the labels"),+ ).toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: /Title/ }));+ const categoryOption = await screen.findByRole("heading", {+ name: "Category",+ });+ expect(+ screen.queryByRole("heading", { name: "ID" }),+ ).not.toBeInTheDocument();+ await userEvent.click(categoryOption);++ await userEvent.click(screen.getByRole("button", { name: "Done" }));+ expect(onSubmit).toHaveBeenCalledWith("card", {+ card_id: 1,+ value_field: ["field", 2, null],+ label_field: ["field", "category", { "base-type": "type/Text" }],+ });+ });++ it("should allow clearing the label field with the None option", async () => {+ const { onSubmit } = await setup({+ parameter: createMockUiParameter({+ values_source_type: "card",+ values_source_config: {+ card_id: 1,+ value_field: ["field", 2, null],+ label_field: ["field", 3, null],+ },+ }),+ cards: [+ createMockCard({+ id: 1,+ name: "Products",+ result_metadata: [+ createMockField({+ id: 2,+ name: "category",+ display_name: "Category",+ base_type: "type/Text",+ effective_type: "type/Text",+ semantic_type: "type/Category",+ }),+ createMockField({+ id: 3,+ name: "title",+ display_name: "Title",+ base_type: "type/Text",+ effective_type: "type/Text",+ semantic_type: "type/Title",+ }),+ ],+ }),+ ],+ });++ await userEvent.click(screen.getByRole("button", { name: /Title/ }));+ const noneOption = await screen.findByRole("heading", { name: "None" });+ await userEvent.click(noneOption);++ await userEvent.click(screen.getByRole("button", { name: "Done" }));+ expect(onSubmit).toHaveBeenCalledWith("card", {+ card_id: 1,+ value_field: ["field", 2, null],+ label_field: undefined,+ });+ });+it("should show card values", async () => {await setup({parameter: createMockUiParameter({diff --git a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsxindex ed237604d16..b48abe7cacb 100644--- a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx+++ b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx@@ -1,4 +1,4 @@-import type { ChangeEvent } from "react";+import type { ChangeEvent, ReactNode } from "react";import { useCallback, useLayoutEffect, useMemo } from "react";import { useAsyncFn } from "react-use";import { jt, t } from "ttag";@@ -277,12 +277,22 @@ const CardSourceModal = ({return query != null ? getSupportedColumns(query, parameter) : [];}, [query, parameter]);+ const labelColumns = useMemo(() => {+ return query != null ? getLabelColumns(query) : [];+ }, [query]);+const selectedField = useMemo(() => {return query != null && sourceConfig.value_field != null? getColumnByReference(query, columns, sourceConfig.value_field): undefined;}, [query, columns, sourceConfig.value_field]);+ const selectedLabelField = useMemo(() => {+ return query != null && sourceConfig.label_field != null+ ? getColumnByReference(query, labelColumns, sourceConfig.label_field)+ : undefined;+ }, [query, labelColumns, sourceConfig.label_field]);+const { values, isError } = useParameterValues({parameter,sourceType,@@ -290,19 +300,32 @@ const CardSourceModal = ({onFetchParameterValues,});- const valuesText = useMemo(- () => getValuesText(getSourceValues(values)),- [values],+ const valuesText = useMemo(() => getValuesText(values), [values]);++ const handleValueFieldChange = useCallback(+ (column: Lib.ColumnMetadata | undefined) => {+ if (query == null || column == null) {+ return;+ }+ onChangeSourceConfig({+ ...sourceConfig,+ value_field: Lib.legacyRef(query, STAGE_INDEX, column),+ });+ },+ [query, sourceConfig, onChangeSourceConfig],);- const handleFieldChange = useCallback(- (event: SelectChangeEvent<Lib.ColumnMetadata>) => {+ const handleLabelFieldChange = useCallback(+ (column: Lib.ColumnMetadata | undefined) => {if (query == null) {return;}onChangeSourceConfig({...sourceConfig,- value_field: Lib.legacyRef(query, STAGE_INDEX, event.target.value),+ label_field:+ column != null+ ? Lib.legacyRef(query, STAGE_INDEX, column)+ : undefined,});},[query, sourceConfig, onChangeSourceConfig],@@ -328,32 +351,34 @@ const CardSourceModal = ({{question ? question.displayName() : t`Pick a model or question…`}</SelectButton></ModalSection>- {question && (- <ModalSection>- <ModalLabel>{t`Column to supply the values`}</ModalLabel>- {query != null && columns.length ? (- <Select- value={selectedField}+ {question && query != null && (+ <>+ <ColumnSelect+ query={query}+ columns={columns}+ selectedColumn={selectedField}+ label={t`Column to supply the values`}+ placeholder={t`Pick a column…`}+ emptyMessage={+ <>+ {getErrorMessage(question, parameter)}{" "}+ {t`Please pick a different model or question.`}+ </>+ }+ onChange={handleValueFieldChange}+ />+ {selectedField != null && labelColumns.length > 0 && (+ <ColumnSelect+ query={query}+ columns={labelColumns}+ selectedColumn={selectedLabelField}+ label={t`Column to supply the labels`}placeholder={t`Pick a column…`}- onChange={handleFieldChange}- >- {columns.map((column, index) => (- <Option- key={index}- name={- Lib.displayInfo(query, STAGE_INDEX, column).displayName- }- value={column}- />- ))}- </Select>- ) : (- <ModalErrorMessage>- {getErrorMessage(question, parameter)}{" "}- {t`Please pick a different model or question.`}- </ModalErrorMessage>+ withNoneOption+ onChange={handleLabelFieldChange}+ />)}- </ModalSection>+ </>)}</ModalPane><ModalMain>@@ -371,6 +396,63 @@ const CardSourceModal = ({);};+interface ColumnSelectProps {+ query: Lib.Query;+ columns: Lib.ColumnMetadata[];+ selectedColumn: Lib.ColumnMetadata | undefined;+ label: string;+ placeholder: string;+ emptyMessage?: ReactNode;+ withNoneOption?: boolean;+ onChange: (column: Lib.ColumnMetadata | undefined) => void;+}++const ColumnSelect = ({+ query,+ columns,+ selectedColumn,+ label,+ placeholder,+ emptyMessage,+ withNoneOption,+ onChange,+}: ColumnSelectProps) => {+ const handleChange = useCallback(+ (event: SelectChangeEvent<Lib.ColumnMetadata | undefined>) => {+ onChange(event.target.value);+ },+ [onChange],+ );++ return (+ <ModalSection>+ <ModalLabel>{label}</ModalLabel>+ {columns.length > 0 ? (+ <Select+ value={selectedColumn}+ placeholder={placeholder}+ onChange={handleChange}+ >+ {[+ ...(withNoneOption+ ? [<Option key="none" name={t`None`} value={undefined} />]+ : []),+ ...columns.map((column, index) => (+ <Option+ key={index}+ name={Lib.displayInfo(query, STAGE_INDEX, column).displayName}+ value={column}+ />+ )),+ ]}+ </Select>+ ) : emptyMessage != null ? (+ <ModalErrorMessage>{emptyMessage}</ModalErrorMessage>+ ) : null}+ </ModalSection>+ );+};+const getErrorMessage = (question: Question, parameter: Parameter) => {const parameterType = getParameterType(parameter);const type = question.type();@@ -509,6 +591,13 @@ const getSupportedColumns = (query: Lib.Query, parameter: Parameter) => {});};+// Labels used for remapping are always text, regardless of the parameter type.+const getLabelColumns = (query: Lib.Query) => {+ return Lib.fieldableColumns(query, 0).filter((column) =>+ Lib.isStringOrStringLike(column),+ );+};+/*** if !hasFields(parameter) then exclude the option to set the source type to* "From connected fields" i.e. values_source_type=nulldiff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsxindex a77ff575ea1..713fbc9526f 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx@@ -47,7 +47,7 @@ import {import { parseNumber } from "metabase/utils/number";import { isNotNull } from "metabase/utils/types";import Field from "metabase-lib/v1/metadata/Field";-import { getSourceType } from "metabase-lib/v1/parameters/utils/parameter-source";+import { hasRemappedParameterValues } from "metabase-lib/v1/parameters/utils/parameter-source";import { normalizeParameter } from "metabase-lib/v1/parameters/utils/parameter-values";import type {CardId,@@ -730,9 +730,7 @@ function RemappedValue({const { uuid, token } = useEmbeddingEntityContext();const entityIdentifier = uuid ?? token ?? null;- const isRemapped =- Field.remappedField(fields) != null ||- getSourceType(parameter) === "static-list";+ const isRemapped = hasRemappedParameterValues(parameter, fields);const { data: dashboardData } = useGetRemappedDashboardParameterValueQuery(dashboardId != null && value != null && isRemappeddiff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/ListField/ListField.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/ListField/ListField.tsxindex b3ca8823b52..71b109a9799 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/ListField/ListField.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/ListField/ListField.tsx@@ -1,4 +1,4 @@-import { useCallback, useMemo, useState } from "react";+import { useCallback, useMemo, useRef, useState } from "react";import { t } from "ttag";import _ from "underscore";@@ -55,6 +55,7 @@ export const ListField = ({const [selectedValues, setSelectedValues] = useState(new Set(normalizedValue),);+ const initiallySelectedValuesRef = useRef(selectedValues);const [addedOptions, setAddedOptions] = useState<Option[]>(() =>createOptionsFromValuesWithoutOptions(normalizedValue, options),);@@ -72,16 +73,10 @@ export const ListField = ({[augmentedOptions, tc],);- /**- * Sorts options alphabetically, or by their translation if content- * translation is enabled. Selected options are sorted to the top. Since- * options are arrays, the last item in the array is used as the name of the- * option.- */const sortOptions = useCallback((optionA: Option, optionB: Option) => {- const aSelected = selectedValues.has(optionA[0]),- bSelected = selectedValues.has(optionB[0]);+ const aSelected = initiallySelectedValuesRef.current.has(optionA[0]);+ const bSelected = initiallySelectedValuesRef.current.has(optionB[0]);if (aSelected && !bSelected) {return -1;@@ -102,14 +97,12 @@ export const ListField = ({? sortByTranslation(aName, bName): 0;},- // eslint-disable-next-line react-hooks/exhaustive-deps -- selectedValues is omitted from the deps so that selecting a value does not trigger re-sorting- [sortByTranslation],+ [optionsHaveSomeTranslations, sortByTranslation],);const sortedOptions = useMemo(- () => augmentedOptions.sort(sortOptions),- // eslint-disable-next-line react-hooks/exhaustive-deps- [augmentedOptions.length, sortOptions],+ () => [...augmentedOptions].sort(sortOptions),+ [augmentedOptions, sortOptions],);const [filter, setFilter] = useState("");diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsxindex 2fe0c3224e2..a841a891b49 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx@@ -1,5 +1,6 @@import { renderNumberOfSelections } from "metabase/parameters/utils/formatting";import Field from "metabase-lib/v1/metadata/Field";+import { hasRemappedParameterValues } from "metabase-lib/v1/parameters/utils/parameter-source";import type { CardId, DashboardId, Parameter } from "metabase-types/api";import { Value } from "../Value";@@ -25,7 +26,9 @@ export function ParameterFieldWidgetValue({const values = normalizeValue(value);const numberOfValues = values.length;const shouldRemap =- Field.remappedField(fields) != null || displayValue != null;+ (parameter != null+ ? hasRemappedParameterValues(parameter, fields)+ : Field.remappedField(fields) != null) || displayValue != null;return numberOfValues > 1 ? (<>{renderNumberOfSelections(numberOfValues)}</>diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/RemappedValue.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/RemappedValue.tsxindex 60b2d126981..3d079a8a6bd 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/RemappedValue.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/RemappedValue.tsx@@ -2,6 +2,7 @@ import type { ReactNode } from "react";import CS from "metabase/css/core/index.css";import AutoLoadRemapped from "metabase/hoc/Remapped";+import { useTranslateContent } from "metabase/i18n/hooks";import { formatValue } from "metabase/visualizations/lib/formatting";import type Field from "metabase-lib/v1/metadata/Field";@@ -16,7 +17,7 @@ type RenderRemapped = (opts: {export type RemappedValueProps = {value: unknown;column?: Field;- displayValue: unknown;+ displayValue?: unknown;displayColumn?: Field;renderNormal?: RenderNormal;renderRemapped?: RenderRemapped;@@ -48,29 +49,48 @@ const RemappedValueContent = ({renderRemapped = defaultRenderRemapped,...props}: Omit<RemappedValueProps, "autoLoad">) => {- if (column != null) {- value = formatValue(value, {- ...props,+ const tc = useTranslateContent();+ const effectiveValue = getEffectiveValue(value, column, props);+ const effectiveDisplayValue = getEffectiveDisplayValue(+ tc(displayValue),+ displayColumn,+ props,+ );+ if (effectiveDisplayValue != null) {+ return renderRemapped({+ value: effectiveValue,+ displayValue: effectiveDisplayValue,column,- jsx: true,- remap: false,- });- }- if (displayColumn != null) {- displayValue = formatValue(displayValue, {- ...props,- column: displayColumn,- jsx: true,- remap: false,+ displayColumn,});- }- if (displayValue != null) {- return renderRemapped({ value, displayValue, column, displayColumn });} else {- return renderNormal({ value, column });+ return renderNormal({ value: effectiveValue, column });}};+const getEffectiveValue = (+ value: unknown,+ column: Field | undefined,+ props: object,+) =>+ column != null+ ? formatValue(value, { ...props, column, jsx: true, remap: false })+ : value;++const getEffectiveDisplayValue = (+ displayValue: unknown,+ displayColumn: Field | undefined,+ props: object,+) =>+ displayColumn != null+ ? formatValue(displayValue, {+ ...props,+ column: displayColumn,+ jsx: true,+ remap: false,+ })+ : displayValue;+export const AutoLoadRemappedValue = AutoLoadRemapped(RemappedValueContent);export const FieldRemappedValue = (props: RemappedValueProps) => (diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/Value.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/Value.tsxindex e4ddae0da8f..b041ff512be 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/Value.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/Value.tsx@@ -33,7 +33,6 @@ export const Value = ({...rawOptions,uuid,token,- displayValue: tc(rawOptions.displayValue),};if (rawOptions.remap) {diff --git a/frontend/src/metabase/redux/metadata.js b/frontend/src/metabase/redux/metadata.jsindex b94bc8ab3b1..42a5845119b 100644--- a/frontend/src/metabase/redux/metadata.js+++ b/frontend/src/metabase/redux/metadata.js@@ -15,6 +15,7 @@ import { isProduction } from "metabase/env";import { createThunkAction } from "metabase/redux";import { DatabaseSchema, FieldSchema } from "metabase/schema";import { RevisionsApi } from "metabase/services";+import { hasRemappedParameterValues } from "metabase-lib/v1/parameters/utils/parameter-source";import { normalizeParameter } from "metabase-lib/v1/parameters/utils/parameter-values";import { updateMetadata } from "./metadata-typed";@@ -218,18 +219,21 @@ export const fetchRemapping = createThunkAction(FETCH_REMAPPING,({ parameter, value, field, cardId, dashboardId, uuid, token }) =>async (dispatch, getState) => {+ if (field != null && field.hasRemappedValue(value)) {+ return;+ }+if (- field == null ||- field.remappedField() == null ||- field.hasRemappedValue(value)+ parameter == null ||+ !hasRemappedParameterValues(parameter, field ? [field] : [])) {return;}const entityIdentifier = uuid ?? token ?? null;-- if (dashboardId != null && parameter != null) {- const remapping = await entityCompatibleQuery(+ let remapping;+ if (dashboardId != null) {+ remapping = await entityCompatibleQuery({...(entityIdentifier? { entityIdentifier }@@ -241,11 +245,8 @@ export const fetchRemapping = createThunkAction(dashboardApi.endpoints.getRemappedDashboardParameterValue,{ forceRefetch: false },);- if (remapping != null) {- dispatch(addRemappings(field.id, [remapping]));- }- } else if (cardId != null && parameter != null) {- const remapping = await entityCompatibleQuery(+ } else if (cardId != null) {+ remapping = await entityCompatibleQuery({...(entityIdentifier ? { entityIdentifier } : { card_id: cardId }),parameter_id: parameter.id,@@ -255,11 +256,10 @@ export const fetchRemapping = createThunkAction(cardApi.endpoints.getRemappedCardParameterValue,{ forceRefetch: false },);- if (remapping != null) {- dispatch(addRemappings(field.id, [remapping]));- }- } else if (parameter != null) {- const remapping = await entityCompatibleQuery(+ } else if (field != null) {+ // Field-based remapping (e.g. FK display fields). Static-list sources+ // carry their [value, label] pairs inline and need no network call.+ remapping = await entityCompatibleQuery({parameter: normalizeParameter(parameter),field_ids: [field.id],@@ -269,9 +269,16 @@ export const fetchRemapping = createThunkAction(datasetApi.endpoints.getRemappedParameterValue,{ forceRefetch: false },);- if (remapping != null) {- dispatch(addRemappings(field.id, [remapping]));- }}++ if (remapping == null) {+ return;+ }++ if (field != null) {+ dispatch(addRemappings(field.id, [remapping]));+ }++ return remapping;},);diff --git a/src/metabase/parameters/custom_values.clj b/src/metabase/parameters/custom_values.cljindex 846759cfa13..60d24a88d9b 100644--- a/src/metabase/parameters/custom_values.clj+++ b/src/metabase/parameters/custom_values.clj@@ -66,15 +66,21 @@[:map;; despite this being called "query string" it can actually be any value because it just gets used in an `:=`;; filter clause. :eyeroll:- [:query-string {:optional true} :any]])+ [:query-string {:optional true} :any]+ ;; when present, the matching column is added as a second breakout so that each row becomes a+ ;; [value label] pair used for remapping+ [:label-field {:optional true} [:maybe [:or :mbql.clause/field :mbql.clause/expression]]]+ ;; when present, restrict the values to an exact match on the value column (used to fetch the+ ;; remapped label for a single selected value)+ [:exact-value {:optional true} :any]])(mu/defn- values-from-card-query :- [:maybe ::lib.schema/query][{query :dataset_query, :keys [id], :as _card} :- [:and:metabase.queries.schema/card[:map[:id ::lib.schema.id/card]]]- field-ref :- [:or :mbql.clause/field :mbql.clause/expression]- {:keys [query-string] :as _opts} :- [:maybe ::values-from-card-query.options]]+ field-ref :- [:or :mbql.clause/field :mbql.clause/expression]+ {:keys [query-string label-field exact-value] :as _opts} :- [:maybe ::values-from-card-query.options]](when (seq query);; start a new query using this Card as a starting point(let [query (lib/query query (lib.metadata/card query id))]@@ -86,17 +92,25 @@id(pr-str field-ref)(pr-str (map (some-fn :lib/source-column-alias :name) visible-columns))))]- (let [textual? (lib.types.isa/string? value-column)+ (let [label-column (when label-field+ (or (lib/find-matching-column query -1 label-field visible-columns)+ (log/warnf "Cannot get labels from Card %d: failed to find column for ref %s"+ id+ (pr-str label-field))))+ textual? (lib.types.isa/string? value-column)nonempty ((if textual? lib/not-empty lib/not-null) value-column)- query-filter (when query-string- (if textual?- (lib/contains (lib/lower value-column) (u/lower-case-en query-string))- (lib/= value-column query-string)))]+ query-filter (cond+ (some? exact-value) (lib/= value-column exact-value)+ query-string (if textual?+ (lib/contains (lib/lower value-column) (u/lower-case-en query-string))+ (lib/= value-column query-string)))](-> query(lib/limit *max-rows*)(lib/filter nonempty)- (cond-> #_query query-filter (lib/filter query-filter))+ (cond-> query-filter (lib/filter query-filter))(lib/breakout value-column)+ ;; add the label as a second breakout so each row is a [value label] pair+ (cond-> label-column (lib/breakout label-column));; TODO(Braden, 07/04/2025): This should probably become a lib helper? I suspect this isn't the only;; "internal" query in the BE.(assoc-in [:middleware :disable-remaps?] true))))))))@@ -135,7 +149,10 @@query-string :- [:maybe ms/NonBlankString]](let [card-id (:card_id config)card (t2/select-one :model/Card :id card-id)]- (values-from-card card (lib/->mbql5 (:value_field config)) {:query-string query-string})))+ (values-from-card card+ (lib/->mbql5 (:value_field config))+ (cond-> {:query-string query-string}+ (:label_field config) (assoc :label-field (lib/->mbql5 (:label_field config)))))))(defn- can-get-card-values?[card value-field]@@ -200,6 +217,21 @@;; more than two groups are always ambiguous, so no matchnil))))))+(mu/defn- card-remapped-value+ "For a card source configured with a `:label_field`, fetch the [value label] pair for a single+ `value` by querying the card filtered to that exact value. Returns nil when there is no label+ field, the card is unreadable/archived, or no matching row is found."+ [{config :values_source_config :as _param} value]+ (when-let [label-field (:label_field config)]+ (when-let [card (t2/select-one :model/Card :id (:card_id config))]+ (when (and (not (:archived card))+ (mi/can-read? card)+ (can-get-card-values? card (:value_field config)))+ (first (:values (values-from-card card+ (lib/->mbql5 (:value_field config))+ {:exact-value value+ :label-field (lib/->mbql5 label-field)})))))))+(mu/defn parameter-remapped-value"Fetch the remapped value for the given `value` of parameter `param` with default values provided bythe function `default-case-thunk`.@@ -211,7 +243,7 @@(case (:values_source_type param):static-list (m/find-first #(and (vector? %) (= (count %) 2) (= (first %) value))(get-in param [:values_source_config :values]))- :card nil+ :card (card-remapped-value param value)nil (default-case-thunk)(throw (ex-info (tru "Invalid parameter source {0}" (:values_source_type param)){:status-code 400diff --git a/test/metabase/parameters/custom_values_test.clj b/test/metabase/parameters/custom_values_test.cljindex ba92b98a992..7c76072bb70 100644--- a/test/metabase/parameters/custom_values_test.clj+++ b/test/metabase/parameters/custom_values_test.clj@@ -36,6 +36,23 @@[:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (mt/id :venues :name)]{:query-string "bakery"}))))))))))+(deftest ^:parallel with-label-field-test+ (testing "providing a label-field adds a second breakout so each row is a [value label] pair"+ (binding [custom-values/*max-rows* 3]+ (mt/with-temp+ [:model/Card card (merge (mt/card-with-source-metadata-for-query (mt/mbql-query venues))+ {:database_id (mt/id)+ :type :question+ :table_id (mt/id :venues)})]+ (is (= {:has_more_values true+ :values [[1 "Red Medicine"]+ [2 "Stout Burgers & Beers"]+ [3 "The Apple Pan"]]}+ (custom-values/values-from-card+ card+ [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (mt/id :venues :id)]+ {:label-field [:field {:lib/uuid "00000000-0000-0000-0000-000000000001"} (mt/id :venues :name)]})))))))+(deftest ^:parallel with-mbql-card-test-2(testing "source card is a model" ; Models are opaque, so this sees the post-aggregation columns.(binding [custom-values/*max-rows* 3]@@ -336,6 +353,69 @@nil(constantly mock-default-result))))))))))+(deftest ^:parallel parameter->values-with-label-field-test+ ;; bind to an admin to bypass the permissions check+ (mt/with-current-user (mt/user->id :crowberto)+ (testing "a card source with a label_field returns [value label] pairs through parameter->values"+ (binding [custom-values/*max-rows* 3]+ (mt/with-temp+ [:model/Card card (merge (mt/card-with-source-metadata-for-query (mt/mbql-query venues))+ {:database_id (mt/id)+ :type :question+ :table_id (mt/id :venues)})]+ (is (= {:has_more_values true+ :values [[1 "Red Medicine"]+ [2 "Stout Burgers & Beers"]+ [3 "The Apple Pan"]]}+ (custom-values/parameter->values+ {:name "Card as source"+ :slug "card"+ :id "_CARD_"+ :type :category+ :values_source_type :card+ :values_source_config {:card_id (:id card)+ :value_field (mt/$ids $venues.id)+ :label_field (mt/$ids $venues.name)}}+ nil+ (fn [] (throw (ex-info "Shouldn't call this function" {})))))))))))++(deftest ^:parallel parameter-remapped-value-card-test+ (mt/with-current-user (mt/user->id :crowberto)+ (testing "a card source with a label_field remaps a single value to a [value label] pair"+ (mt/with-temp+ [:model/Card card (merge (mt/card-with-source-metadata-for-query (mt/mbql-query venues))+ {:database_id (mt/id)+ :type :question+ :table_id (mt/id :venues)})]+ (is (= [1 "Red Medicine"]+ (custom-values/parameter-remapped-value+ {:name "Card as source"+ :slug "card"+ :id "_CARD_"+ :type :category+ :values_source_type :card+ :values_source_config {:card_id (:id card)+ :value_field (mt/$ids $venues.id)+ :label_field (mt/$ids $venues.name)}}+ 1+ (fn [] (throw (ex-info "Shouldn't call this function" {}))))))))+ (testing "a card source without a label_field has no remapped value"+ (mt/with-temp+ [:model/Card card (merge (mt/card-with-source-metadata-for-query (mt/mbql-query venues))+ {:database_id (mt/id)+ :type :question+ :table_id (mt/id :venues)})]+ (is (nil? (custom-values/parameter-remapped-value+ {:name "Card as source"+ :slug "card"+ :id "_CARD_"+ :type :category+ :values_source_type :card+ :values_source_config {:card_id (:id card)+ :value_field (mt/$ids $venues.id)}}+ 1+ (fn [] (throw (ex-info "Shouldn't call this function" {}))))))))))+(deftest ^:parallel order-by-aggregation-fields-test(testing "Values could be retrieved for queries containing ordering by aggregation (#46369)"(doseq [model? [true false]]