Categories
jQuery and SP Services SharePoint SharePoint 2010

Using SPServices “GetGroupCollectionFromUser” operation

SharePoint 2010 Used

We had a task in which we had to show and hide items on a page based on which group a user belonged to.
We needed a way to identify if the current user belonged to a specific group. We were able to accomplish this using the “GetGroupCollectionFromUser” operation of SPServices.
Lets say you had a site with many groups but 5 of them were “Finance”. To identify “Finance”, it was appended with “_FIN”.

Using “GetGroupCollectionFromUser” operation, here’s the function that was created.

A function DecideGroup(url) with one parameter called ‘url’ was created.

see below:


function DecideGroup(url)
{
var url = siteUrl+"/";
var isFIN;
var bsoGrpName=null;
$().SPServices({
operation: "GetGroupCollectionFromUser",
userLoginName: $().SPServices.SPGetCurrentUser(),
async: false,
webURL: url,
completefunc: function(xData, Status) {
$(xData.responseXML).find("Group[Name$='_FIN']").each(function() { //find any group ending in '_FIN'
finGrpName = $(this).attr("Name");
return false; //Once you find they are in a finance group, no need to go continue with the loop
});
}

});
return finGrpName; //return group name
}

Categories
jQuery and SP Services SharePoint SharePoint 2010

Creating a SharePoint Site Hierarchy Chart

Note: This post assumes you know a little about “SharePoint“, “jQuery“, “SPServices“, “Google Charts” and “HTML

The other day I was asked by our client to create a site collection chart showing the relationships between all the sites and sub-sites in the site collection.  This would be similar to an organizational chart showing the hierarchy in leadership except in this instance, I would be showing the hierarchy in sites.  They also wanted the chart to show all the users with full ownership of the sites.

I knew that SharePoint out of the box could not help with the task at hand so that option was out of the question.  I then remembered that Google provides a JavaScript API that would allow for the creation of an organizational chart.  BINGO!

All I needed to do now was talk to the Farm administrator to create and run a script that would provide me all the sites and their parent sites along with all the users that have full ownership of their respective sites.  Once the data was provided in excel, all I did was transfer it over to SharePoint in datasheet view in the correct format that the google org chart requires and used a combination of jQuery and SPServices to get the data from my SharePoint list to feed the chart for visualization.

Here is a link to my list and the data. As you will see, I have four columns, “Name”, “ReportTo”, “Users” and “ToolTip”.  The first 2 columns is what’s needed for all the magic to occur.  The “Name” will be all the sites in the site collection and “ReportTo” lists all the parent sites of the sites in the “Name” column.  The “users” contains all the site admins of each site.

Here is what the code looks like:

</pre>
<style><!--
.myNodeClass {     text-align: center;     vertical-align: middle;     font-family: arial,helvetica;     font-size: 25px;     cursor: default;     border: 2px solid #b5d9ea;     -moz-border-radius: 5px;     -webkit-border-radius: 5px;     -webkit-box-shadow: rgba(0, 0, 0, 0.5) 3px 3px 3px;     -moz-box-shadow: rgba(0, 0, 0, 0.5) 3px 3px 3px;     background-color: #CCC;     background: -webkit-gradient(linear, left top, left bottom, from(#CCC), to(#b0d7ee)); } .mySelectedNodeClass {     border: 2px solid #e38493;     background-color: #eeeeee;     background: -webkit-gradient(linear, left top, left bottom, from(#eeeeee), to(#dddddd)); }
--></style>
<script type="text/javascript">
	      google.load('visualization', '1', {packages: ['orgchart']});
		  google.setOnLoadCallback(drawChart);

function drawChart()
{
	//alert("HELLO");

	//alert($().SPServices.SPGetCurrentSite());
	 // Initialize data object to hold chart data
	 var data = new google.visualization.DataTable();
	 data.addColumn('string', 'Name');
	 data.addColumn('string', 'ReportTo');
	 data.addColumn('string', 'Tool tip');
	 
	 var name="";
	 var ReportTo="";
	 var ToolTip="";
	 var OrgName="";
	 
	 //alert("before spserv");
	 $().SPServices({
		operation: "GetListItems",
		async: false,
		listName: "OrgChart",
			//CAMLRowLimit: 0,
		CAMLViewFields: "<ViewFields><FieldRef Name='Title'></FieldRef><FieldRef Name='Users'></FieldRef><FieldRef Name='Name'></FieldRef><FieldRef Name='ToolTip'></FieldRef><FieldRef Name='ReportToOrg'></FieldRef><FieldRef Name='OrgName'></FieldRef></ViewFields>",     
		CAMLQuery: "<Query><OrderBy><FieldRef Name='Order0' Ascending='False' /></OrderBy></Query>",
		completefunc: function (xData, Status) {			
			// Loop through each item 
				
				$(xData.responseXML).SPFilterNode('z:row').each(function() {													
					//OrgName=$(this).attr("ows_OrgName");	
					//name = "{v:'"+$(this).attr("ows_Name")+"', f:'<font color='red'>test</font>'},'',''";
					if ($(this).attr("ows_Name")=="BAH")
					{
						name = {
							v: $(this).attr("ows_Name"),
							f: "<font color='blue'><u>Site Name</u><br></font>" + $(this).attr("ows_Name") + "<br><br><font color='blue'><u>Site Admins</u><br></font><font color='#800000'><img src=" + $(this).attr("ows_ToolTip") + " /></font>"
						};					
					}
					else
					{
						name = {
							v: $(this).attr("ows_Name"),
							f: "<font color='blue'><u>Site Name</u><br></font>" + $(this).attr("ows_Name") + "<br><br><font color='blue'><u>Site Admins</u><br></font><font color='#800000'>" + $(this).attr("ows_Users") + "</font>"
						};
					}
					
					//alert("name: "+name);
					ReportTo = $(this).attr("ows_Title");
					//ReportTo = $(this).attr("ows_ReportToOrg");
					
					ToolTip = $(this).attr("ows_ToolTip");	
						
					data.addRow([name, ReportTo, ToolTip]);
				});
				}		
	});				

        var chart = new google.visualization.OrgChart(document.getElementById('VisualizeOrgChart'));
        chart.draw(data, {
            allowHtml:true,
            nodeClass: 'myNodeClass',
            selectedNodeClass: 'mySelectedNodeClass',
            size: 'large'
        });	  
        
google.visualization.events.addListener(chart, 'select', function() {
          // grab a few details before redirecting
          var selection = chart.getSelection();
          var ArrayIndex = selection[0].row;         
          var Item = data.getValue(ArrayIndex, 0);
          
          alert("row: "+ArrayIndex);         
          alert("You can redirect to a page to show just this Item: "+Item);                    
          });        
        
        
   }
<div id="VisualizeOrgChart" style="width: 300px; height: 300px;"></div>
<pre>

Here is the actual chart.

Hope that made sense to you.

Happy SharePointing!!

Categories
jQuery and SP Services SharePoint SharePoint 2010

Creating Google Bar Chart in SharePoint 2010

In my last blog post, I wrote about creating a Pie Chart in SharePoint using Google charts. In this post, I will show how to create a bar chart using the same data. It’s going to be a short post because it requires changing one line.

Before I proceed to the purpose of this post, I wanted to first share some information I found on knowing when to use the right type of chart. It’s always convey your data in a manner that makes sense. I found the following sites to be useful.

For the sake of example, my posts just show how to use Google chart and not necessarily focused on selecting the right one.

Now that we have that out of the way, to convert the pie chart to a bar chart, all you have to do is change the following line:

var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

to

var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

Now you are probably wondering, how is this able to work? Well, if you remember in my last post, I talked about how every chart has a data format that needs to be followed. Here’s the data format for both pie and bar charts:

Pie Chart
Rows: Each row in the table represents a slice.

Bar Chart
Rows: Each row in the table represents a group of bars.

As you can see the data format is similar and that’s why we are able to change one line of code to make it work.

To render it in SharePoint, I created another content editor web part on the same page as my Pie Chart and I also created another file called BuildBarChart.html with the following code in it:

</pre>
<div id="BarChart_div" style="width: 650px; height: 500px;"> </div>
<pre>

I also created a function called drawBarChart() but has the same exact code as my pieChart. The only difference is the line I talked about above.

Here’s the code of the function:

function drawBarChart(BinderItems,PencilItems,PenItems,PenSetItems,DeskItems) {
 //alert("Desk Items: "+DeskItems);
        var data = google.visualization.arrayToDataTable([
          ['Items', 'Number of Items Available'],
          ['Binder', BinderItems],
          ['Pencils', PencilItems],
          ['Pen Set', PenSetItems],
          ['Pen', PenItems],
          ['Desk', DeskItems]
        ]);

        var options = {
          title: 'Available School Items',
          is3D:true,
          titleTextStyle: {color: 'black', fontName:'"Verdana"', fontSize: '12'},
          legend:  { textStyle: {color: 'black', fontName: '"Arial"', fontSize: '12'}}
        };

      var chart = new google.visualization.BarChart(document.getElementById('BarChart_div'));
        chart.draw(data, options);
}

Here are both charts side by side. Pie and Bar Charts
Please share your comments. I would appreciate feedback. Thanks!

Categories
jQuery and SP Services SharePoint SharePoint 2010

Google Chart & SharePoint

Lately, I have been involved with a lot of Google Chart work.  For those of you that don’t know, Google Charts allows you to create different kinds of graphs to visualize your data.  These kinds of graphs include: Pie Charts, Bar Charts, Line Charts, Table Charts, etc.
You can check out the rest of the charts in the chart gallery found here.

If you are not familiar with what a SharePoint list is, here’s a good place to start to learn (SharePoint List).

In this post, my goal is to share how I’ve created Google charts using a SharePoint list as a data source.  The data I will be using has been exported into my SharePoint list and you can read where to get this data from in my last post.

I am going to show you how to create a pie chart using the data from my last post.  My pie chart will be based on the total percentage of  “Pens,Pencils,Desk,PenSet and Binder” in a company.

First, open up notepad, SharePoint Designer 2010 or whatever you use for coding.  Next, to begin to create your google chart, the following libraries are required and can be loaded using the Script links in your js file.  Also, don’t forget to load your jQuery and SPServices library.

  • The Google JSAPI API (Loads the needed API’s)
  • The Google Visualization library (“This library defines all the core utility classes and functions.”)

Once you have have your data and your libraries are loaded, you are ready to use SPServices and jQuery to create the code that will draw the chart based on your provided data in your list.  The draw() method requires two parameters to draw your chart and it is “data” and “options”.  As long as you provide those two based on the type of chart, you should be good to go.

Every chart stores their data in a table and each has a different format for their data and how it should be prepared.  Always look through the documentation of the chart you want to find out table formats.
Here’s what google says…“Different charts use tables in different formats: for example, a pie chart expects a two-column table with a string column and a number column, where each row describes a slice, and the first column is the size label and the second column is the slice value. A scatter chart, however, expects a table consisting of two numeric columns, where each row is a point, and the two columns are the X and Y values of the point. Read your chart’s documentation to learn what data format it requires.”   –Google Charts Site

So, here’s what my pie chart table will look like:

var data = google.visualization.arrayToDataTable([
   ['Region Sales', 'Items Available'],
['Binder', BinderItems],
['Pencils', PencilItems],
['Pen Set', PenSetItems],
['Pen', PenItems],
['Desk', DeskItems]
]);

Each of the rows starting with ‘Binder’ to ‘Desk’ is a slice in my pie chart.  I use SPservices and jQuery to loop through the “SampleData” list and provide the data for each item.

Once your data and your options are ready to go, you can now draw your chart by providing the following code:

var options = {
title: 'Available School Items',
is3D:true,
titleTextStyle: {color: 'black', fontName:'"Verdana"', fontSize: '12'},
legend: { textStyle: {color: 'black', fontName: '"Arial"', fontSize: '12'}}
};

var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

chart.draw(data, options);

Once you are done with the .js file, create a web part page.  You can then add a content editor web part to the page and link it to your .js file.

Here’s a link to the pie chart in SharePoint – Pie Chart.  The code below shows how I put it all together.

</pre>
<table>
<tbody>
<tr>
<td> </td>
</tr>
</tbody>
</table>
<pre>
<!-- Begin Javascript and JQuery -->
<span style="color: #339966;">//load all your libraries</span>
<script type="text/javascript" src="http://issharepoint.com/isdemosite/Script/jquery-1.8.2.min.js" language="javascript"></script><script type="text/javascript" src="http://issharepoint.com/isdemosite/Script/jquery.SPServices-0.7.2.min.js" language="javascript"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script><script type="text/javascript">// <![CDATA[
google.load("visualization", "1", {packages:["corechart"]});

$(document).ready(function() {
<span style="color: #339966;">//Initialize your variables.  Will be used later to capture the value of each item as it's added up</span>
var Pencils=0;
var Binder=0;
var Desk=0;
var PenSet=0;
var Pen=0;

$().SPServices({
    operation: "GetListItems",
    async: false,
    listName: "SampleData",  //Here's my list name
    CAMLViewFields: "<ViewFields></ViewFields>",
	CAMLRowLimit: 0,
	CAMLQuery:"<Query></Query>",
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {   //Loops through each list item
<span style="color: #339966;">//adds the values depending on the item
</span>
		if($(this).attr("ows_Item") == "Binder")
		{
			Binder += $(this).attr("Units");
		}
		else if( ($(this).attr("ows_Item") == "Pencil"))
		{
			Pencils += $(this).attr("Units");
		}
		else if( ($(this).attr("ows_Item") == "Pen"))
		{
			Pen += $(this).attr("Units");
		}
		else if( ($(this).attr("ows_Item") == "Pen Set"))
		{
			PenSet += $(this).attr("Units");
		}
		else if( ($(this).attr("ows_Item") == "Desk"))
		{
			Desk += $(this).attr("Units");
		}
      });

     }

  });
<span style="color: #339966;">//Passes the values into a function that will draw my chart
</span>
 drawChart(Binder,Pencils,Pen,PenSet,Desk);
});
 function drawChart(BinderItems,PencilItems,PenItems,PenSetItems,DeskItems) {
<span style="color: #339966;">//Puts the values in a data table that the pie chart needs.  Remember that every row is a slice
</span>
        var data = google.visualization.arrayToDataTable([
          ['Region Sales', 'Items Available'],
          ['Binder', BinderItems],
          ['Pencils', PencilItems],
          ['Pen Set', PenSetItems],
          ['Pen', PenItems],
          ['Desk', DeskItems]
        ]);

<span style="color: #339966;">//Cart Options shows title, font-color, legend and I want the chart to show in 3D
</span>
var options = {
          title: 'Available School Items',
          is3D:true,
          titleTextStyle: {color: 'black', fontName:'"Verdana"', fontSize: '12'},
          legend:  { textStyle: {color: 'black', fontName: '"Arial"', fontSize: '12'}}
        };
<span style="color: #339966;">//Finds my div and draws my chart there
</span>
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
}
<table>
	<tr><td><div id="chart_div" style="width: 900px; height: 500px;"></div></td></tr>
</table>

// ]]></script>

I hope that makes sense.
// ]]>