Sync filters for multiple Flexmonster instances

Slice configuration

by Flexmonster Pivot Table

HTML

<script src="https://cdn.flexmonster.com/flexmonster.js"></script>

<div>
  <h2>How to sync filters for multiple Flexmonster instances</h2>
  <p>
    In this example, we sync filters for two Flexmonster instances. These
    instances are subscribed to the
    <a href="https://www.flexmonster.com/api/reportchange/" target="_blank"
    >reportchange</a> event, which is triggered when you change the report.
  </p>
  <p>
    So, when you filter a field, the <code>syncFilters()</code> function is
    called. It uses the
    <a href="https://www.flexmonster.com/api/getfilter/" target="_blank"
    >getFilter()</a> and
    <a href="https://www.flexmonster.com/api/setfilter/" target="_blank"
    >setFilter()</a> methods to pass filters from one Flexmonster instance 
    to another (lines 56-65 in the JavaScript box).
  </p>
  <p>
    Try setting filters in any Flexmonster instance and see how they are
    synchronized.
  </p>
</div>

<div id="pivot-container1" style="margin-bottom: 12px"></div>

<div id="pivot-container2"></div>

CSS

@import url(https://cdn.flexmonster.com/assets/jsfiddle-styles.css);

JavaScript

let pivot1 = new Flexmonster({
  container: "pivot-container1",
  componentFolder: "https://cdn.flexmonster.com/",
  height: 250,
  report: {
    dataSource: {
      filename: "data/data.csv"
    },
    slice: {
      reportFilters: [{
        uniqueName: "Country"
      }],
      rows: [{
        uniqueName: "Color"
      }],
      columns: [{
        uniqueName: "[Measures]"
      }],
      measures: [{
        uniqueName: "Price"
      }]
    }
  },
  reportchange: () => {
    syncFilters(pivot1, pivot2);
  }
});

let pivot2 = new Flexmonster({
  container: "pivot-container2",
  componentFolder: "https://cdn.flexmonster.com/",
  height: 250,
  report: {
    dataSource: {
      filename: "data/data.csv"
    },
    slice: {
      columns: [{
        uniqueName: "Color"
      }],
      rows: [{
        uniqueName: "Country"
      }, {
        uniqueName: "[Measures]"
      }],
      measures: [{
        uniqueName: "Quantity"
      }]
    }
  },
  reportchange: () => {
    syncFilters(pivot2, pivot1);
  }
});

function syncFilters(pivotFrom, pivotTo) {
  pivotTo.off("reportchange");
  const hierarchies = pivotFrom.getAllHierarchies();
  hierarchies.forEach((item) => {
    pivotTo.setFilter(item.uniqueName, pivotFrom.getFilter(item.uniqueName));
  });
  pivotTo.on("reportchange", () => {
    syncFilters(pivotTo, pivotFrom);
  });
}