Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Reply
Anonymous
Not applicable

Visual filtering using Advanced Filter API

Hi All,

 

I was trying to use the Advanced Filter API for a simple text filter.

 

I can see the visuals reloading, whenever I press the filter buttons in the visual, but I don't see any data being filtered.

 

Any idea on what am I missing? I created the general object with the filter property in the capabilities.json file and I am using applyJsonFilter method to invoke the filter

 

capabilities.json:

 

{
  "dataRoles": [
    {
      "displayName": "Text Fields",
      "name": "textFields",
      "kind": "Grouping"
    }
  ],
  "objects": {
    "general": {
      "displayName": "General",
      "properties": {
        "filter": {
          "type": {
            "filter": true
          }
        }
      }
    }
  },
  "dataViewMappings": [
    {
      "conditions": [
        {
          "textFields": {
              "max": 1
          }
        }
      ],
      "table":{
          "rows": {
              "select": [
                  {
                      "for": { "in": "textFields"}
                  }
              ],
              "dataReductionAlgorithm": {
                "top": {
                    "count": 30000
                }
              }
          }
      }
    }
  ]
}

 

visual.ts:

/*
*  Power BI Visual CLI
*
*  Copyright (c) Microsoft Corporation
*  All rights reserved.
*  MIT License
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the ""Software""), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  The above copyright notice and this permission notice shall be included in
*  all copies or substantial portions of the Software.
*
*  THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/
"use strict";

import "core-js/stable";
import "./../style/visual.less";
import powerbi from "powerbi-visuals-api";
import * as models from "powerbi-models";
import { VisualSettings } from "./settings";
import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
import IVisual = powerbi.extensibility.visual.IVisual;
import IVisualHost = powerbi.extensibility.visual.IVisualHost;
import IFilterColumnTarget = models.IFilterColumnTarget;
import IAdvancedFilterCondition = models.IAdvancedFilterCondition;
import FilterAction = powerbi.FilterAction;
import IAdvancedFilter = models.IAdvancedFilter;
import AdvancedFilter = models.AdvancedFilter;
import VisualObjectInstanceEnumeration = powerbi.VisualObjectInstanceEnumeration;

/**
 * Interface for search text view model.
 */
interface ViewModel {
    filterColumns: IFilterColumnTarget[];
};

export class Visual implements IVisual {
    private host: IVisualHost;
    private viewModel: ViewModel;
    private target: HTMLElement;
    private searchBox: HTMLInputElement;
    private searchButton: HTMLButtonElement;
    private clearButton: HTMLButtonElement;
    private selectConditionOperator: HTMLSelectElement;

    constructor(options: VisualConstructorOptions) {
        this.host = options.host;
        this.target = options.element;
        this.target.innerHTML = `<div class="text-filter-search">
                                    
                                    <select name="Operator" id="operator" class="operationSelector">
                                        <option value="Contains">Contains</option>
                                        <option value="StartsWith">Starts with</option>
                                        <option value="DoesNotContain">Does not contain</option>
                                        <option value="DoesNotStartWith">Does not start with</option>
                                    </select>
                                    <div class="wrapper">

                                        <input aria-label="Enter your search" type="text" name="search-field">
                                        <div class="button-container">  

                                            <button class="c-glyph clear-button" name="clear-button">
                                            <span class="x-screen-reader">Clear</span>
                                            </button>

                                            <button class="c-glyph search-button" name="search-button">
                                            <span class="x-screen-reader">Search</span>
                                            </button>
                                        </div>
                                    </div>

                                </div>`;

        this.selectConditionOperator = this.target.getElementsByClassName("operationSelector")[0] as HTMLSelectElement;
        this.searchBox = this.target.getElementsByTagName("input")[0] as HTMLInputElement;
        this.searchButton = this.target.getElementsByClassName("search-button")[0] as HTMLButtonElement;
        this.clearButton = this.target.getElementsByClassName("clear-button")[0] as HTMLButtonElement;
    }

    public update(options: VisualUpdateOptions) {
        //Get data
        this.viewModel = this.getViewModel(options);

        //print data
        console.log(this.viewModel);

        //add keyboard event to the search box
        this.searchBox.addEventListener("keydown", (e) => {
            if (e.key == 'Enter') {
                this.performFilter(this.viewModel.filterColumns[0], this.selectConditionOperator.value, this.searchBox.value);
            }
        });

        //add click events to the buttons
        this.clearButton.addEventListener("click", () => this.performFilter(this.viewModel.filterColumns[0], this.selectConditionOperator.value,""));
        this.searchButton.addEventListener("click", () => this.performFilter(this.viewModel.filterColumns[0], this.selectConditionOperator.value, this.searchBox.value));
    }
    
    private getViewModel(options: VisualUpdateOptions): ViewModel{
        //declare the data view
        let dataView = options.dataViews[0];
        let tableDataView = dataView.table;

        //set an empty view model
        let viewModel: ViewModel = {
            filterColumns: []
        };

        //return empty view model if there's no data to show
        if (!tableDataView
            || !tableDataView.rows
            || !tableDataView.columns) {
            return viewModel;
        }
        
        //declare columns
        let cols = tableDataView.columns;

        //iterate cols and push the columns properties to the view model
        cols.forEach(col => {
            viewModel.filterColumns.push(
                {table: col.queryName.substr(0, col.queryName.indexOf('.')),
                column: col.displayName
                }
            )
        });

        return viewModel;
    }

    private performFilter(target: IFilterColumnTarget, operator: any, text: string) {
        let filter: IAdvancedFilter = null;
        let action = FilterAction.remove;

        //Check if searched text is blank
        if(text.length > 0){
            //set conditions
            let conditions: IAdvancedFilterCondition[] = [];
            conditions.push({
                operator: operator,
                value: text
            });
            
            //create the filter
            filter = {
                $schema: "http://powerbi.com/product/schema#advanced",
                ...(new AdvancedFilter(target, "And", conditions))
            }

            //set the action to merge
            FilterAction.merge
        }
        //clear search box if text is blank
        else{
            this.searchBox.value = null;
        }
              
        //print filter
        console.log(filter);

        // invoke the filter
        this.host.applyJsonFilter(filter, "general", "filter", action);
    }
}

 

Thank you for any feedback you can provide me.

1 ACCEPTED SOLUTION
dm-p
Super User
Super User

Hi @Anonymous

This one just about drove me to the point where I was convinced there was a bug in the API... filters are tricky as they get sent to the visual host to process, and if they aren't just right, then they don't get applied, so I spent way too long on debugging that syntax, which is fortunately all good 🙂

The issue turns out to be this line:

 

//set the action to merge
FilterAction.merge

 

Because you have assigned the action variable as FilterAction.remove higher up, this code doesn't actually update the variable and the applyJsonFilter's action value was always asking the visual host to remove the filter rather than apply it.

Based on your current implementation, it should be:

 

//set the action to merge
action = FilterAction.merge

 

By doing this, I was able to get the code to work.

Hopefully that gets you back on track. Good luck!

Daniel

 

 
 




Did I answer your question? Mark my post as a solution!

Proud to be a Super User!


My course: Introduction to Developing Power BI Visuals


On how to ask a technical question, if you really want an answer (courtesy of SQLBI)




View solution in original post

2 REPLIES 2
dm-p
Super User
Super User

Hi @Anonymous

This one just about drove me to the point where I was convinced there was a bug in the API... filters are tricky as they get sent to the visual host to process, and if they aren't just right, then they don't get applied, so I spent way too long on debugging that syntax, which is fortunately all good 🙂

The issue turns out to be this line:

 

//set the action to merge
FilterAction.merge

 

Because you have assigned the action variable as FilterAction.remove higher up, this code doesn't actually update the variable and the applyJsonFilter's action value was always asking the visual host to remove the filter rather than apply it.

Based on your current implementation, it should be:

 

//set the action to merge
action = FilterAction.merge

 

By doing this, I was able to get the code to work.

Hopefully that gets you back on track. Good luck!

Daniel

 

 
 




Did I answer your question? Mark my post as a solution!

Proud to be a Super User!


My course: Introduction to Developing Power BI Visuals


On how to ask a technical question, if you really want an answer (courtesy of SQLBI)




Anonymous
Not applicable

What a rookie mistake. Thank you for spotting it! It's working now! 🙂

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.

April Fabric Community Update

Fabric Community Update - April 2024

Find out what's new and trending in the Fabric Community.