Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / SharePoint / SharePoint2010

Orgnization Chart in SharePoint

4.67/5 (2 votes)
27 Sep 2013CPOL2 min read 23.8K   506  
Article shows to create a simple org/orgnization chart in sharepoint 2010.

Download OrgChart.zip

Introduction

This is the third post of JQuery With SharePoint 2010 series. Please read the first one, how to Integrate/use
JQuery with SP 2010
. There are multiple ways to create Organization Chart in SharePoint including the out of box one. Here I would like to discuss and share the code, using which you can create simple organization chart web part.

I would like accomplish following things in the article.

  • Create a simple list of employees with their managers.
  • Read the list to generate the Organization chart using a JQuery Plugin.

Prerequisites:

  • Download JQuery from Here
  • Download JQuery plugin jOrgChart from here.

*** Please download the .zip file get full code

Image 1

Org Chart Web Part

Create a Visual Web Part with the following structures.

  • OrgChartWebPartUserControl.ascx: Fetchs employees from the organization list and formats the content as required by the JQuery Plugin.
  • Layouts: Contains all the JQuery, JOrgChart Plugin and Images files.
  • OrgChart List Feature will create a list “OrgChart”, which is pre-populated with some dummy data. Visual web part is going to pick up the employee list from here.

 
Image 2

OrgChart List Feature

This feature will create a list which will store the employee list of an organization. List has following columns.

  • Employee
  • Designation
  • Manager

You can add email, phone number columns based on your requirements. For now, I would like to keep it simple.

Following code is added in FeatureActivated method.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //Get the SPWeb instance
            var web = properties.Feature.Parent as SPWeb;
            if (web == null)
                return;

            //Add OrgList and enable Quick launch
            var listId = web.Lists.Add("OrgChart", "Organization Structure", SPListTemplateType.GenericList);
            var list = web.Lists[listId];
            list.OnQuickLaunch = true;
            list.Update();
            
            //Get the title field and hide it, so that it is not visible while you add new items to the list
            var title = list.Fields["Title"];
            title.Hidden = true;
            title.Update();

            //Add item field and enforece uniquness
            var empName = list.Fields.Add("Employee", SPFieldType.Text, true);
          
            //Add designation field
            var designation = list.Fields.Add("Designation", SPFieldType.Text, true);

            //Adding manager with look up field pointing to the item column
            var manager = list.Fields.AddLookup("Manager", list.ID, false);
            SPFieldLookup managerField = (SPFieldLookup)list.Fields[manager];
            managerField.LookupField = list.Fields["Employee"].InternalName;
            managerField.Update();


            //******//
            //You can additional fields like picture, email , phote, location etc....
            //******//

            //Hide the title from default view
            var view = list.DefaultView;
            if (view.ViewFields.Exists("LinkTitle"))
            {
                view.ViewFields.Delete("LinkTitle");
            }

            //Add the column to the default view
            view.ViewFields.Add(empName);
            view.ViewFields.Add(designation);
            view.ViewFields.Add(manager);
            view.Update();

            //Add some default values to the list
            var item1 = list.Items.Add();
            item1[empName] = "John";
            item1[designation] = "CEO";
            item1.Update();

            var item2 = list.Items.Add();
            item2[empName] = "Steve";
            item2[designation] = "CTO";
            item2[manager] = new SPFieldLookupValue(item1.ID, item1[empName].ToString());
            item2.Update();

            var item3 = list.Items.Add();
            item3[empName] = "Tom";
            item3[designation] = "COO";
            item3[manager] = new SPFieldLookupValue(item1.ID, item1[empName].ToString());
            item3.Update();

            var item4 = list.Items.Add();
            item4[empName] = "Andrew";
            item4[designation] = "Sr VP";
            item4[manager] = new SPFieldLookupValue(item2.ID, item2[empName].ToString());
            item4.Update();

            var item5 = list.Items.Add();
            item5[empName] = "Mary";
            item5[designation] = "Sr VP";
            item5[manager] = new SPFieldLookupValue(item3.ID, item3[empName].ToString());
            item5.Update();

            var item6 = list.Items.Add();
            item6[empName] = "Thomas";
            item6[designation] = "Sr VP";
            item6[manager] = new SPFieldLookupValue(item4.ID, item4[empName].ToString());
            item6.Update();

            var item7 = list.Items.Add();
            item7[empName] = "Test";
            item7[designation] = "XYZ";
            item7.Update();
        }

Following code is added in FeatureDeactivating method. This will ensure that the list is deleted when the feature is deactivated. You can comment out this code, if you want the list to remain after deactivation.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    var web = properties.Feature.Parent as SPWeb;
    if (web == null)
        return;
    var list = web.Lists.TryGetList("OrgChart");
    list.Delete();
}

Visual Web Part: OrgChartWebPartUserControl.ascx

This has the code to retrieve data from list and format as required by the JQuery Plugin. Code behind:
    public partial class OrgChartWebPartUserControl : UserControl
    {
        string orgDOMstart = "Html Format issue - Downlod code and check";
        string orgBody = string.Empty;
        string orgDOMEnd = "";
        string childRecords = string.Empty;
        List<splistitem> listItems = null;
        string image = string.Empty;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            BuildOrgChart();
        }

        /// <summary>
        /// Method will build the org chart html, which will be used by the JQuery plugin to rendered the org chart UI.
        /// </summary>
        private void BuildOrgChart()
        {

            string spWebUrl = SPContext.Current.Web.Url;

            //Get the OrgChart list items
            using (var site = new SPSite(spWebUrl))
            {
                var web = site.RootWeb;
                var list = web.Lists.TryGetList("OrgChart");
                listItems = GetListItemsAsList(list.Items);
            }

            //Get tol level nodes(employees), whom managers are not assigned.
            var topLevelNodes = listItems.Where(i => ((i["Manager"] == null) ? "" : i["Manager"].ToString()) == "").ToList<splistitem>();

            foreach (var item in topLevelNodes)
            {
                //For each top node recursively build the html
                GenerateChilRecords(item);
                orgBody = orgBody + childRecords;
                childRecords = string.Empty;
            }

            //Assign the HTML to a Label text.
            lblChartHtml.Text = orgDOMstart + orgBody + orgDOMEnd;
        }

        /// <summary>
        /// Method used to recursively to build the chart html
        /// </summary>
        /// <param name="item" />
        private void GenerateChilRecords(SPListItem item)
        {
            //Get the reportees
            var empReportees = listItems.Where(i => ((i["Manager"] == null) ? "" : i["Manager"].ToString().Split('#')[1]) == item["Employee"].ToString()).ToList<splistitem>();

            //Add the collpase image, if there are any reportess for the employee
            if (empReportees.Count > 0)
            {
                image = "Collapse Image - Downlod code and check";
            }

            childRecords = childRecords + "<li>" + image + " <span style="font-size: 0.9em;">" + item["Employee"] + "</span>
<span style="font-size: 0.8em;">  " + item["Designation"] + "</span>";
            //if there are any reportess for the employee, call the method recursively to check if reportees have any reportess under them.
            if (empReportees.Count > 0)
            {
                childRecords = childRecords + "<ul>";
                foreach (var employee in empReportees)
                {
                    GenerateChilRecords(employee);
                }
                childRecords = childRecords + "</ul></li>";
            }
            else
            {
                childRecords = childRecords + "";
                return;
            }
        }

        /// <summary>
        /// Method returns list of SPListItem, upon which we can use LINQ queries
        /// </summary>
        /// <param name="liCol" />
        /// <returns>
        private List<splistitem> GetListItemsAsList(SPListItemCollection liCol)
        {
            List<splistitem> toReturn = new List<splistitem>();
            foreach (SPListItem li in liCol)
            {
                toReturn.Add(li);
            }
            return toReturn;
        }
    }

</splistitem></splistitem></splistitem></returns></splistitem></splistitem></splistitem>

HTML:

<link href="../../../_layouts/OrgChart/Include/prettify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    jQuery(document).ready(function () {
        $("#org").jOrgChart({
            chartElement: '#chart',
            dragAndDrop: true
        });
    });

    var mynode;
    function fnExpand(node) {
        if (image.attr("src") == '../../../_layouts/OrgChart/Img/Collapse.png') {
            image.attr("src", '../../../_layouts/OrgChart/Img/Expand.png')
        }
        else {
            image.attr("src", '../../../_layouts/OrgChart/Img/Collapse.png')
        }
    }
</script>
<asp:label id="lblChartHtml" runat="server">

Code has been improvised to add expand and collapse images. There are other ways to create org charts including the COTS products. If you are looking for a simple solution, then you can try this and improvise.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)