Forum Discussion

Ankan2508's avatar
Ankan2508
Advocate II
7 months ago
Solved

UDF not working

I have created a UDF, but it is showing multiple errors. Can anybody resolve this? createOrReplace     function 'XU.Sparkline.MinMax' =             (                 XAxis : SCALAR VAL,  ...
  • AshokKunwar's avatar
    AshokKunwar
    7 months ago

    If you want to use this as a "Function" without creating a standard measure for every visual, you must use the DEFINE syntax in the DAX Query View.

    Step 1: The "Function" Definition

    ​You cannot use createOrReplace. Instead, use the DEFINE VAR syntax. This allows the logic to act as a function within the scope of your query.

    DEFINE
        -- This acts as your "UDF" logic
        MEASURE 'Table'[XU.Sparkline.MinMax] = 
        VAR LineColour = "#0078D4"
        VAR MaxColour = "#228B22"
        VAR MinColour = "#DC143C"
        VAR PointColour = "%23FFFFFF"
        
        -- Your SVG Logic here...
        VAR MaxX = [MaxX_Logic] 
        VAR MaxY = [MaxY_Logic]
        
        RETURN 
        "data&colon;image/svg+xml;utf8,<svg ...>" & 
        "<circle cx='" & MaxX & "' cy='" & 50 - MaxY & "' ... />" & 
        "</svg>"
    
    -- This part executes the "Function"
    EVALUATE
    SUMMARIZECOLUMNS(
        'Table'[Category],
        "Sparkline", 'Table'[XU.Sparkline.MinMax]
    )

     

    Step 2: Why the createOrReplace syntax is failing

    ​The createOrReplace syntax is part of TMSL (Tabular Model Scripting Language) or C# scripts used in Tabular Editor—it is not valid DAX code that can be pasted into the formula bar.

    • If using Power BI Desktop: Use a Measure.
    • If using Tabular Editor: Use the Scripting window to deploy the measure to the model metadata.

    Step 3: Handling the SVG String

    ​To ensure the "UDF" output renders as an image:

    1. ​Ensure the return string starts with data&colon;image/svg+xml;utf8,.
    2. ​Ensure you have escaped the # symbol as %23 if your colors aren't rendering in certain browsers.

    Technical Summary

    ​While Power BI doesn't have a specific "UDF" object, the DAX Query View is the designated environment for defining and testing function-like logic before committing it to the model as a Measure.