6/23/2012

Creating Percentage Totals for Every Line in Views

Using percentages, it is just not possible to create a correct value for every row in a view, if you are aggregating upwards.

Here is an Example: Calculating the revenue change in comparison to the last year, displaying as percent.

As all amounts are summed up, they could not be automatically be compared and written as a percentage using notes mechanisms (if you go on and sum up the percentage values, you end up with terrible off numbers, contact me if you have a better alternative).

So here is a nice workaround:

Using a $$ViewTemplateDefault (or $$ViewTemplate for FormName), the view can be opened in a web container (even in notes, using Single Sign-On) and use the following code in the "onLoad" event to dynamically update the percentages in the row, and you are done.

In my example i use one column containing the absolute sums, accumulated over categories, from the last year, and the amount of change (you could easily adapt the code to work for absolute last year versus absolute this year).


//nodes are differently styled with font / b etc
function innerText(node){
 while(node && node.firstChild)
  node=node.firstChild;
 if(node && node.data)
  return node.data;
 else
  return '';
}

function setInnerText(node,text,styleColor){
 if(!node)
  return;
 while(node.firstChild)
  node=node.firstChild;
 node.data=text;
 if(node.parentNode&&node.parentNode.style)
  node.parentNode.style.color=styleColor;
}

//get url param
function getUrlParam( name )
{
 name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

 var regexS = "[\\?&]"+name+"=([^&#]*)";
 var regex = new RegExp( regexS );
 var results = regex.exec( window.location.href );

 if ( results == null )
  return "";
 else
  return results[1];
}

// get the table
table = document.getElementsByTagName('table')[0];
//leftmost cell is usually merged if categorized
//so count from the right side
lastYearColFromRight = 10;
changeColFromRight = 4;
outputColFromRight = 2;

if(table){
 //first row is header
 for (i = 1; i < table.rows.length; i += 1) {
    row = table.rows[i];

    len = row.cells.length;
    num = innerText(row.cells[len-lastYearColFromRight]);
    lastYear = Number((num==""|num==null)?0:num);
    change = Number(innerText(row.cells[len-changeColFromRight]));
    //do not divide by zero
    if(lastYear==0){
     percent = 0;
     if(change!=null)
      //output absolute amounts if last year was zero
      outString=change.toFixed(2)+" A";
     else
      outString="0.00 %";
    }
    else{
      percent=(change/lastYear)*100
     outString=percent.toFixed(2)+' %';
    }
    // determine cell color
    color=percent<0?'red':'black';
    //set value
    setInnerText(row.cells[len-outputColFromRight],outString,color);
 }
}

No comments:

Post a Comment