Organization Chart using Visualforce and Google Visualization API

1:42 PM

The below diagram is what we are going to build. This hierarchy is based upon the manager field in the user object. The below example is NOT based upon the role hierarchy. Anyhow, you can modify the code below to fit the role hierarchy.

Visualforce Page:

<apex:page controller="orgchart" showHeader="false">
  <html>
  <head>
    <script type='text/javascript' src='https://www.google.com/jsapi'></script>
    <script type='text/javascript'>
      google.load('visualization', '1', {packages:['orgchart']});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('string', 'Manager');
        data.addColumn('string', 'ToolTip');
      
        data.addRows([
         
          {!userdata}
         
        ]);
        var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
        chart.draw(data, {allowHtml:true});
      }
    </script>
  </head>

  <body>
 
    <div id='chart_div' style="font-size:18px;"></div>
  </body>
</html></apex:page>

Apex Class
public class orgchart {

Public String getuserdata()
{
    List<User> allusers = [Select Name,Manager.Name from User where IsActive = TRUE and ManagerId != NULL];
    String datastr = '';
    for (integer i=0;i<allusers.size();i++)
    {
        datastr = datastr + '[\'';
        datastr += allusers[i].Name;
        datastr+= '\',\'';
        datastr+= allusers[i].Manager.Name;
        datastr+='\',\'\'],';
    } 
    datastr = datastr + '';
    return datastr;

}   
}

9 comments

  1. This is nice, how can we modify this so the chart fits the hierarchy ?

    ReplyDelete
  2. Ho to do a multi-level hierarchy? How many levels are possible?

    ReplyDelete
  3. I think there is no limit on the level of hierarchy, you can just keep adding datarows and the hierarchy expands

    ReplyDelete
  4. This will not work, until we need to remove the comma at the end. Include this line after the for loop ends.
    ........
    ........
    datastr = datastr.substring(0, datastr.length() -1);
    datastr = datastr + '';
    return datastr;

    ReplyDelete
  5. Thanks for pointing that out Viswa. Also, it looks like a single datastr variable can display a maximum of 50 separate hierarchy divisions..

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Thanks,This is nice information about organizations.
    A big thank you for your blog article.Organization charts definitely help to structure the employees and work flow environment.

    ReplyDelete
  8. I am getting this error System.StringException: Ending position out of bounds: -1
    can any one why it is coming

    ReplyDelete
  9. I used the same code but i didnt got any output.can any one help

    ReplyDelete

AD