6 Replies Latest reply on Nov 8, 2013 8:56 AM by Russell Christopher

    Set default date filter to show last 3 months using javascript api

    Sylvia Lawrence

      Hi guys,

       

      I created a dashboard on Tableau Desktop and published it to our Tableau server. I have a date filter that's a multi-select dropdown with all the dates in 'MMMMYY' format.

      I'm trying to create a simple webpage using Tableau's Javascript API to change the default date filter to always show the last 3 months data on page load (i.e as the default).

      I tried the following code but I get the error: "Uncaught Error: Another viz is already present in element 'div#viz'. "

       

      $(document).ready(function()

      {

      $(window).load(function () {

        var vizDiv = document.getElementById('viz');

        var vizURL = "https://URL-to-my-dashboard";

        var options = {

        width: '600px',

        height: '540px',

        hideToolbar: true,

        hideTabs: true,

        onFirstInteractive: function () {

        workbook = viz.getWorkbook();

        document.getElementById('sheetName').innerHTML = viz.getWorkbook().getActiveSheet().getName();

        }

        };

        viz = new tableauSoftware.Viz(vizDiv, vizURL, options);

        viz.addEventListener('tabswitch', function(event) {

        document.getElementById('sheetName').innerHTML = event.getNewSheetName();

        });

      });

       

       

      $(window).load(function () {

        showLastNMonths('Date', 3);

      });

      });

       

      function showLastNMonths(filter, months, anchor) {

        sheet = viz.getWorkbook().getActiveSheet();

        var dateObj;

        if(anchor) {

        dateObj = new Date(anchor);

        } else {

        dateObj = new Date();

        }

        if(sheet.getSheetType() === 'worksheet') {

        sheet.applyRelativeDateFilterAsync(filter, {

        periodType: 'month',

        rangeType: 'lastn',

        rangeN: months,

        anchorDate: dateObj

        });

        } else {

        worksheetArray = sheet.getWorksheets();

        for(var i = 0; i < worksheetArray.length; i++) {

        worksheetArray[i].applyRelativeDateFilterAsync(filter, {

        periodType: 'month',

        rangeType: 'lastn',

        rangeN: months,

        anchorDate: dateObj

        });

        }

        }

      }

      Any thoughts on why I get that error is much appreciated.. and also how to solve it? How do I set default as last 3 months?

      Thanks,

      Sylvia

        • 1. Re: Set default date filter to show last 3 months using javascript api
          Russell Christopher

          Sylvia -

           

          The message indicates that you're trying to insert a second viz into a div which already contains a viz. You'd probably have to step through your code to see if that's actually the case. Maybe $(window).load is getting called multiple times?

           

          In any case, here's a sample of how to do what you want, minus the other stuff in your code...

           

          function applyRelativeDateFilterAsync() {
          
          
              mainWorkbook = mainViz.getWorkbook();
          
          
              var onSuccess = function (sheet) {
                  // Change anchor date to Dec 1, and switch filter from "Last 4 years" to "lastRange376 days"
                  sheet.applyRelativeDateFilterAsync(
                      "Ship Date", {
                      anchorDate: new Date("12/1/2012"),
                      periodType: tableauSoftware.PeriodType.DAY,
                      rangeType: tableauSoftware.DateRangeType.LASTN,
                      rangeN: 376
                  });
              };
          
          
              var onError = function (err) {
                  alertOrConsole("Whoops");
              };
          
              var newSheet = mainWorkbook.activateSheetAsync('Shipped by Date').then(onSuccess, onError);
          }
          

           

          You'll need to change the PeriodType to Month, of course.

          • 2. Re: Set default date filter to show last 3 months using javascript api
            Murali Govindu

            Hi Russell,

             

            I hope Sylvia might have got his Answer.

             

            I have similar interest in know on how to get last 8 months upon each data load, and can it be without the coding stuff and be through the Cal. fields, etc..?

             

            Also, the values for the dates from the database is showing '201204' i.e., year and quarter and I am unable to format it '2012 Q4'.  I am currently making the date as string passing on to the dashboard so it is howing 201201  201301 and so on.

             

            Any clue?

             

            Thanks and regards,

            murali.govindu@gmail.com

            • 3. Re: Set default date filter to show last 3 months using javascript api
              Russell Christopher

              Hi Murali -

               

              It seems your question isn't really related to Syliva's since you're not interested in JavaScript. Please re-post your question with a bit more detail?

               

              Regards!

              • 4. Re: Set default date filter to show last 3 months using javascript api
                Murali Govindu

                Thanks Russell, I thought so, but want to avoid any similar posts!  I shall do it in sometime.

                • 5. Re: Set default date filter to show last 3 months using javascript api
                  Sylvia Lawrence

                  Hi Russell,

                   

                  Does that mean I have to call the applyRelativeDateFilterAsync() function on windows.load?

                  • 6. Re: Set default date filter to show last 3 months using javascript api
                    Russell Christopher

                    Nope. You can do all of this in document.ready – there’s no real reason to do it in windows.load unless I’m missing something.

                     

                    Unfortunately, the approach that you’re taking will require you to first render the report, then filter it – which essentially re-renders it.  This isn’t a great experience from the user’s perspective but there’s not much you can do if you want to use relative dates.

                     

                    One thing you might consider is detailed here:

                     

                    http://community.tableau.com/thread/122964

                     

                    This has nothing to do with JavaScript, but at the end of the thread, someone comes up with a good way to kinda/sorta create a workable equivalent of relative dates. If you were to go this route, the advantage would be that you could set the date filter AS you render the report — no “rendering twice”. You’d set the date values in the options that you pass when you render:

                     

                        var mainVizDiv = $("#mainViz");

                        var mainWorkbookUrl = "http://" + serverName + "/t/SkunkWorks/views/JavaScriptTarget/Dashboard";

                        var mainVizOptions =

                        };

                        //  Create viz

                        mainViz = new tableauSoftware.Viz(mainVizDiv[0], mainWorkbookUrl, mainVizOptions);

                     

                     

                    I’ve never tried to combine these two approaches, but I see no reason why it wouldn’t work.