Combo Filtering Using the Chart Legend!

Shmuel Kamensky
edited September 3, 2016 in General
Hello guys and gals!

I'm Shmuel and I'm a new Skuider.

I've been learning skuid for about 1 or 2 months now and it is a life changer.
It's one of those tools that is so easy to use, it becomes a gateway for learning more complex things (kind of like Salesforce itself...).
I become more and more impressed each day. It's like Skuid has thought of everything possible (not saying there's not room for growth though).

But it's not only the tool itself that's great, the Skuid community is chock full of information and contributions.

Here's a small contribution to give back! It's one of those 'use at your own risk' kind of things given that I'm completely new to javascript and web development (my experience is mainly in Apex). So, forgive the bad practices when you find them! And also let me know about them :).

The idea behind this snippet came from a user. When presented with a pie chart, he wanted to be able to select multiple parts of the pie and see the data below.
So I put a before render snippet and using the Highcharts API, utilized the onclick event for legendItems.
Now, you can select any combination of a set of points in a series, and the snippet will query another model using the points selected.
My use case was to allow for the user to choose a combination of stages, compare the aggregate data and display data about those stages below.

I didn't specify in the comments, but I found a few functions unavailable from highcharts which is why you may see some code that looks like it could have been done with a highchart provided method (or I just missed it).

You can put this sample page in a developer org (it will look better if there's some data in it).

Thanks to Rob Hatch who's post here led me to the world of HighCharts :)

<skuidpage unsavedchangeswarning="yes" personalizationmode="server" showsidebar="true" showheader="true">
<models> <model id="OpportunityAggregate" limit="" query="true" createrowifnonefound="false" adapter="salesforce" type="aggregate" sobject="Opportunity"> <fields> <field id="Id" name="countdistinctId" function="COUNT_DISTINCT"/> </fields> <conditions/> <actions/> <groupby method="simple"> <field id="StageName" name="stageName"/> </groupby> </model> <model id="OpportunityDetail" limit="500" query="false" createrowifnonefound="false" adapter="salesforce" type="" sobject="Opportunity"> <fields> <field id="StageName"/> <field id="Attachments" type="childRelationship" limit="10"> <fields> <field id="Id"/> <field id="Name"/> </fields> </field> <field id="OpportunityContactRoles" type="childRelationship" limit="10"> <conditions/> <fields> <field id="Contact.Name"/> </fields> </field> <field id="OpportunityCompetitors" type="childRelationship" limit="10"> <fields> <field id="CompetitorName"/> </fields> </field> <field id="OpportunityLineItems" type="childRelationship" limit="10"> <fields> <field id="Name"/> </fields> </field> </fields> <conditions logic=""> <condition type="multiple" value="" field="StageName" operator="in" enclosevalueinquotes="true" state="filterableon" inactive="false" name="StageNames"> <values> <value/> <value/> </values> </condition> </conditions> <actions/> </model> </models> <components> <skuidvis__chart model="OpportunityAggregate" maintitle="Opportunties" type="pie" uniqueid="sk-3jSKYn-178" rendersnippet="ChartLegendFilter"> <dataaxes> <axis id="axis1"/> </dataaxes> <categoryaxes> <axis id="categories" categorytype="field"/> </categoryaxes> <serieslist> <series valuefield="countdistinctId" splittype="template" modelId="OpportunityAggregate" splittemplate="{{{stageName}}}" aggfunction="sum"/> </serieslist> <colors/> <legend layout="horizontal" halign="center" valign="bottom"/> <renderconditions logictype="and"/> </skuidvis__chart> <skootable showconditions="true" showsavecancel="false" showerrorsinline="true" searchmethod="server" searchbox="true" showexportbuttons="false" pagesize="50" createrecords="false" model="OpportunityDetail" buttonposition="" mode="readonly" uniqueid="sk-3jSgRb-196"> <fields> <field id="Name" valuehalign="" type=""/> <field id="StageName" valuehalign="" type=""/> <field id="OpportunityContactRoles" type="CHILDREL" limit="100" valuehalign="" allowhtml="true"> <label>Contact Roles</label> <template>&lt;ul style="margin: 0; padding: 0;"&gt; &lt;li&gt;{{Contact.Name}}&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;</template> </field> <field id="OpportunityCompetitors" type="CHILDREL" limit="100" valuehalign="" allowhtml="true"> <label>Competitors</label> <template>&lt;ul style="margin: 0; padding: 0;"&gt; &lt;li&gt;{{CompetitorName}}&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;</template> </field> <field id="OpportunityLineItems" type="CHILDREL" limit="100" valuehalign="" allowhtml="true"> <label>Line Items</label> <template>&lt;ul style="margin: 0; padding: 0;"&gt; &lt;li&gt;{{Name}}&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;</template> </field> <field id="Attachments" type="CHILDREL" limit="100" valuehalign="" allowhtml="true"> <label>Attachments</label> <template>&lt;ul style="margin: 0; padding: 0;"&gt; &lt;li&gt;&lt;a href="/{{{Id}}}" target="_blank"&gt;{{Name}}&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </template> </field> </fields> <rowactions/> <massactions usefirstitemasdefault="true"/> <views> <view type="standard"/> </views> <searchfields/> <renderconditions logictype="and"/> </skootable> </components> <resources> <labels/> <javascript> <jsitem location="inlinesnippet" name="ChartLegendFilter" cachelocation="false">var chartObj = arguments[0], $ = skuid.$; $.extend(true, chartObj, { chart : { backgroundColor: "#FFFFFF" }, tooltip: { enabled: false }, plotOptions: { pie: { events: { afterAnimate: function() { SetAllPointsToVisible(); } }, allowPointSelect: true, point: { events: { legendItemClick: function() { try { //feed point to main filter handler filterBySelectedItems(this); } catch (eForError) { console.log(eForError); } } } }, dataLabels: { enabled: true, formatter: function() { return + ' ' + this.point.y + ' (' + this.percentage.toFixed(2) + '%)'; } } } } }); //since the point.visible attribute isn't accessible before the legenditem/point is clicked, //we need to set all points to visible function SetAllPointsToVisible() { //get all of the points in your series //WARNING I ONLY HAD ONE SERIES, YOU MAY HAVE TO DO THIS FOR //ALL SERIES. var points = chartObj.series[0].data; try { for (i = 0; i &lt; points.length; i++) { var point = points[i];; point.visible = true; } } catch (e) { console.log(e); } } //this is where you update the conditions function updateConditions(conditionList) { oppLegacyMod = skuid.model.getModel('OpportunityDetail'); //remove all rows if there are any oppLegacyMod.emptyData(); //get condition var stageConditions = oppLegacyMod.getConditionByName('StageNames'); //update query condition oppLegacyMod.setCondition(stageConditions, conditionList); //update model oppLegacyMod.updateData(); } //each time a legendItem is clicked, this function is called //to get the currently clicked legenditems as of this click function CreateActivePointsList(currentPoint) { var activePointsList = Array(); //get all points var points = chartObj.series[0].data; //iterate over all points for (i = 0; i &lt; points.length; i++) { //declare a point for the current iteration var point = points[i]; //exception for the current point which was just clicked via the UI //since its 'visible' attribute doesn't change until after the onclick event has finished //basically the value you want (post click) is the opposite of what the registered attribute value is //(pre click) if ( == &amp;&amp; currentPoint.visible) { continue; } else if ( == { activePointsList.push(; continue; } if (point.visible) { activePointsList.push(; } } return activePointsList; } //need to store active points in sessionStorage //since each time a legend item is clicked, a new context is started, and variables are not //saved across contexts function CreateSessionStorageArray() { //check to see if the storage item was created this session if (sessionStorage.getItem("activePoints") === null) { //if it hasn't been, create it var activePointsTemp = []; sessionStorage.setItem("activePoints", activePointsTemp.toString()); } } function GetActivePointsGlobal() { //get and return activePoints return sessionStorage.getItem("activePoints"); } function timedModelUpdate(timeToBlockUIFuncVar, activePointsFuncVar) { //declare array which will be populated by the sessionStorage variable var activePointsGlobal = []; //sessionStorage items are stored as strings. //Since the active points object is an array, it's stored as a comma separated list // and can be converted back into an array with the string.split() method activePointsGlobal = GetActivePointsGlobal().split(","); //make sure that the list of points that this snippet has calculated as active is the most current //list (the user could have clicked on different points since then) var isSame = JSON.stringify(activePointsFuncVar) === JSON.stringify(activePointsGlobal); //if the lists are the same it means that this snippet is the last run snippet // - from the time the initial click was made to the until the amount of time to wait has elapsed. //Therefore, use these values as they are current! if (isSame) { //block the UI so the user doesn't click anymore legend items before the query had a chance to be retrieved and displayed skuid.$.blockUI({ message: 'Populating Table With Selected Options', timeout: timeToBlockUIFuncVar }); //update the conditions with the points calculated from this snippet //(or whatever context-local variable(s) you want to populated it with) //the updatedata is called within the update conditions function updateConditions(activePointsFuncVar); //set active points to an empty string just in case it ever gets referenced elsewhere (not 100% necessary) sessionStorage.setItem("activePoints", ""); } } function filterBySelectedItems(pointClicked) { //active points as of the time the legendItem was clicked var activePoints = CreateActivePointsList(pointClicked); //create sessionStorage if one hasn't been created already CreateSessionStorageArray(); //overwrite sessionStorage with current list since the list we want will always //be the last clicked list sessionStorage.setItem("activePoints", activePoints.toString()); //time to wait from last click until you're done waiting for the user to finish inputting //this gives the user time to choose different options. //in milliseconds var timeToWait = 2000; //time to block UI for in milliseconds var timeToBlockUI = 2000; //launch timeout function //the point of the logic in the timeout function is to make sure only the last clicked legend item's snippet is acted on //(i.e it will run the update conditions). //if the snippet is not from the last clicked legend item otherwise it will do nothing setTimeout( function() { timedModelUpdate(timeToBlockUI, activePoints); }, timeToWait); }</jsitem> </javascript> <css/> </resources> <styles> <styleitem type="background" bgtype="none"/> </styles> </skuidpage>
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!