You can apply filters to display a subset of the data available for a view. You can either apply filters before a visualization has been loaded (at initialization) or after (interactively).
Important: If you want to limit or control the content users see in the embedded view, don't rely on filters as a form of security. While the filters you apply can initially limit what users see, the filters could also be cleared or reverted by toolbar buttons or other controls in Tableau.
If you want to filter data based on the user that requests it, it's best to use user attributes and implement row-level security. See Customize and Control Data Access Using User Attributes and Overview of Row-Level Security Options in Tableau.
In this section
You can apply filters on the viz by adding <viz-filter>
elements to your <tableau-viz>
web component. This is only supported in <tableau-viz>
web components. You can’t apply filters to <tableau-authoring-viz>
components.
The <viz-filter>
element has two attributes: the field
and its value
.
<viz-filter field="name" value="value"> </viz-filter>
The filter can contain multiple values, and you can add multiple <viz-filter>
elements to the <tableau-viz>
component.
Note that when a filter contains multiple values, the values should be comma-delimited (,) without spaces.
When you specify fields in a filter, you should use the caption as shown in the Tableau viz (user interface), not the database field name. The field names are case-sensitive. In some cases, Tableau Desktop renames fields after they’ve been dragged to a shelf. For example the Date field might be renamed to YEAR(Date)
after being dragged to the rows shelf. In this case, you should use YEAR(Date)
as the name of the field. The exception is hierarchical filters, which use the full hierarchical name (for example, [Product].[All Product].[Espresso]
). Captions can use the optional []
delimiters around names.
Here’s example code that adds two filters to a <tableau-viz>
web component.
<script type="module" src="https://public.tableau.com/javascripts/api/tableau.embedding.3.latest.min.js"></script>
<tableau-viz id="tableauViz"
src='https://public.tableau.com/views/Superstore_24/Overview'
toolbar="bottom" hide-tabs>
<viz-filter field="Category" value="Technology"> </viz-filter>
<viz-filter field="State" value="California,Oregon,Washington"> </viz-filter>
</tableau-viz>
To see what it looks like when you embed this code in a page, see Example of filtering.
If you prefer to use JavaScript to embed your views, you can still apply filters during initialization by using the addFilter()
method. To do this you add the filters on the TableauViz
object before you render the view. For example, the following snippet applies two filters (Central, West) to the view and then renders the view by appending it to the HTML element that has the identifier, tableauViz
.
let url = 'https://public.tableau.com/views/Superstore_24/Overview';
// create the viz object
const viz = new TableauViz();
viz.src = url;
// configure the viz...
// apply filters
viz.addFilter('Region', 'Central,West');
// render the view by appending it to "tableauViz"
document.getElementById('tableauViz').appendChild(viz);
To apply filters after you have initialized and rendered the view, use the applyFilterAsync
or applyRangeFilterAsync
methods, see Apply filters interactively (after initialization). If you use the addFilter()
method after initialization, the view is re-rendered.
As an alternative to using the applyFilter()
method, you could create a filter element and append that to the TableauViz
object directly before initialization. For example, the following snippet shows how you might apply a filter on the Region field so that it only shows the West.
// assumes a viz object has been created
const filter = document.createElement("viz-filter");
filter.setAttribute("field", "Region");
filter.setAttribute("value", "West");
viz.appendChild(filter);
// render the view by appending it to "tableauViz"
document.getElementById('tableauViz').appendChild(viz);
You can use the applyFilterAsync()
and applyRangeFilterAsync
methods to apply filters after your visualization has loaded. To do this, you first need to create a JavaScript object from the web component <tableau-viz>
. After you have the viz
object, you can use the Embedding API methods to interact with the view.
Use the applyFilterAsync()
method to filter the view based on a list of categorical filter values. For example, the following code shows how you might filter a single value. In this case, the field is State
and the value is Washington
. Note that the applyFilterAsync
method requires an array of values, so you must include the brackets ([ ]
) even if you are filtering on a single value.
When you call the applyFilterAsync()
method, you also need to specify what action you want to take. You can either add a new filter, replace, or remove existing filters, or apply all filters. To specify the action, use the FilterUpdateType
enumerations (FilterUpdateType.Replace
, FilterUpdateType.Add
, FilterUpdateType.Remove
, FilterUpdateType.All
).
Note if you are embedding a view from Tableau 2021.4, you need to use the string literal values ("replace"
, "add"
, "all"
, "remove"
), instead of the FilterUpdateType
enumerations (for example, FilterUpdateType.Replace
).
// assumes a <tableau-viz> was created with the id='tableauViz'
let viz = document.getElementById('tableauViz');
let sheet = viz.workbook.activeSheet;
const saleMap = sheet.worksheets.find(ws => ws.name =="SaleMap");
saleMap.applyFilterAsync("State", ["Washington"], FilterUpdateType.Replace);
To filter using multiple values, separate the filter values with commas (,
).
saleMap.applyFilterAsync("State", ["Washington","Oregon"], FilterUpdateType.Replace);
To add additional filters, use the action FilterUpdateType.Add
.
saleMap.applyFilterAsync("State", ["Ohio"], FilterUpdateType.Add);
To remove filters, use the action FilterUpdateType.Remove
.
saleMap.applyFilterAsync("State", ["Oregon"], FilterUpdateType.Remove);
You can filter on ranges using the applyRangeFilterAsync
method. For example, to set a range on a date field, use the RangeFilterOptions
properties, min
and max
to set the range. Note that the dates must be in UTC format.
saleMap.applyRangeFilterAsync("Order Date", {
min: new Date(Date.UTC(2018, 3, 1)),
max: new Date(Date.UTC(2020, 08, 30))
});
You can use the getFiltersAsync
methods to retrieve the collection of filters in a workbook. The dashboard.getFiltersAsync
method returns the list of filters used on the dashboard. The worksheet.getFiltersAsync
method returns the list of filters in a worksheet. From the filters returned, you can use the filter properties to determine the filter types and their applied values.
To retrieve the collection of filters used in a dashboard, use the dashboard.getFiltersAsync
method. The method returns all the filters in the dashboard, including range filters, relative date filters, hierarchical filters, and categorical filters. Note that you can only apply categorical filters to a dashboard.
The following example shows how you might retrieve the collection of filters used in the dashboard. From the list of filters (dashFilters
), the example uses FilterType.Categorical
to find only the categorical filters and then prints those to the Console. If you check for filter type in your code, be sure to import FilterType
when you import the Embedding API v3 library.
const dashFilters = await dashboard.getFiltersAsync();
// show # and names of categorical filters in the Console
const categoricalFilters = dashFilters.filter((df) => df.filterType === FilterType.Categorical);
console.log(categoricalFilters);
To retrieve the collection of filters used in a worksheet, use the worksheet.getFiltersAsync
method.
The following example gets the list of filters in a worksheet and prints the list to the Console.
const sheetFilters = await worksheet.getFiltersAsync();
console.log(sheetFilters);
In some cases you might want to find the current filter settings before applying new values. You can do this by retrieving the filter object and then checking the filter properties. For categorical and hierarchical filters, you can use the filter.appliedValues
properties. For range and relative date filters, you can examine other properties, such as minValue
, maxValue
, or anchorDate
.
For example, if you want to track how your users are applying and changing filters in the viz, you could set up an event handler to track whenever a FilterChangedEvent
occurs, and record information about the filters used.
The following example selects a specific categorical filter (Region
) from the worksheet and then uses the filter.appliedValues
property to find the current setting.
// get the array of filters in the worksheet
const sheetFilters = await worksheet.getFiltersAsync();
// Get the filter we want to use
const filter = sheetFilters.find((fs) => fs.fieldName === 'Region');
// Get the filter values and print those values to the Console
const fvals = filter.appliedValues;
console.log(`Filter values: ${fvals.map((v) => v.value)}`);
The following example selects a relative date filter (Order Date
) and prints out the currently applied values to the console, the anchor date, period type (days, months, years, etc.), and the range type (current, next N, last N, etc. ).
// Get applied filter values (date range)
// Get the filters in the sheet
const sheetFilters = await worksheet.getFiltersAsync();
// Get the filter we want to use
const filter = sheetFilters.find((fs) => fs.fieldName === 'Order Date');
// check for relative-date values
console.log(`Filter type: ${filter.filterType}`);
console.log(`AnchorDate: ${filter.anchorDate.formattedValue}`);
console.log(`Period: ${filter.periodType}`);
console.log(`RangeType: ${filter.rangeType}`);
The following example shows what it looks like when you filter the view during initialization, using the web component. The buttons show what happens when you apply filters interactively after the initial load. This example adds two filters to a <tableau-viz>
web component when the embedded viz if first loaded.
<script type="module" src="https://public.tableau.com/javascripts/api/tableau.embedding.3.latest.min.js"></script>
<tableau-viz id="tableauViz"
src='https://public.tableau.com/views/Superstore_embedded_800x800/Overview'
toolbar="bottom" hide-tabs>
<viz-filter field="Category" value="Technology"> </viz-filter>
<viz-filter field="State" value="California,Oregon,Washington"> </viz-filter>
</tableau-viz>
The Oregon and Washington Only button, runs the following code when the button is clicked:
function filterState() {
let viz = document.getElementById("tableauViz");
console.log( viz);
let sheet = viz.workbook.activeSheet;;
const saleMap = sheet.worksheets.find((ws) => ws.name == "SaleMap");
saleMap.applyFilterAsync("State", ["Washington", "Oregon"], FilterUpdateType.Replace);
};
The Clear Filter button, calls the clearFilterAsync()
method:
function clearState() {
let viz = document.getElementById("tableauViz");
console.log( viz);
let sheet = viz.workbook.activeSheet;
const saleMap = sheet.worksheets.find((ws) => ws.name == "SaleMap");
saleMap.clearFilterAsync("State");
The Undo button calls the undoAsync()
method on the viz object and reverts the previous action.
function unDo() {
let viz = document.getElementById("tableauViz");
viz.undoAsync();
};