Sunday, February 7, 2016

How to create a year Calendar in SharePoint 2013



We have come across a requirement that where we need to show all meetings or users leave information in Year Calendar with colors. Below is the image that has come up final view after implementation. To implement this we need to use Jquery and SPservices to fetch data from list.


There is a known issue with reading of date fields values from Jquery client side object model. Value will be converted automatically to our local timezone and this need to be converted to the SharePoint site timezone .


It took few minutes to render the year calendar code from Google and simple SharePoint client side programming to fetch records to bind it to the respective place holders.








There could be better ways to do it and below is the full code to generate this calendar:


<html>
<head>
<script type="text/jscript" src="../jquery-1.10.2.js"></script>
<script src="../jquery.SPServices-2014.02.min.js" type="text/jscript"></script>
<style type="text/css">
.weekend
{
    color:black;
    background-color:Aqua;
}
.tblmonth td
{
  
      border: 1px solid black;
        
     font-family:Segoe UI;
      font-size:14px;
    border-spacing:0;
   
   
}
.calyear
{
    font-family:Segoe UI;
    font-size:20px;
    border-spacing:0;
}
.tblmonth table,.calyear table {
    border-collapse: collapse;
    border-spacing: 0;
}
.clscheckbox,.clsallcheckbox
{

 float:left;
 padding-right:10px;
}
</style>
<script language="javascript" type="text/javascript">
    var strBody = '';
    $(document).ready(function () {
        var categoryFieldInternalName = 'User_x0020_name';
        var categoryFieldDisplayName = 'User name';
        var bgcolors = ["red", "blue", "coral", "maroon", "green", "Fuchsia","black"];
        var catColor = '';
        var colorCounter = 0;
        $("#divcategory").append("<div class='clsallcheckbox' style='float:left' id='divslctall'><input class='clscategoryall'
type='checkbox' id='selecctall' value='All'/>All</div>");
        LoadSiteList();
        //////////////////////
        function LoadSiteList() {
            $().SPServices({
                operation: "GetList",
                listName: "Calendar",
                completefunc: function (xData, Status) {
                    getChoiceField(xData, Status);
                },
                async: false
            });
        }
        ///////////////////////////
  //Select all checkboxes
   $('#selecctall').click(function(event) {  //on click
          if(this.checked) { // check select status
              $('.clscategory').each(function() { //loop through each checkbox
                  this.checked = true;  //select all checkboxes with class "clscategory"              
              });
          }else{
              $('.clscategory').each(function() { //loop through each checkbox
                  this.checked = false; //deselect all checkboxes with class "clscategory"                      
              });        
          }
      });
      $('.clscategory').click(function(event) {  //on click of individual checkbox clear select all checkbox
          if(!this.checked) { // check select status            
                $('.clscategoryall').each(function() { //loop through each checkbox
                   this.checked = false; //deselect all checkboxes with class "clscategory"                      
               });                      
             }
      });
      ///////////////////////
      /////////////Get choice field values
        function getChoiceField(xData, Status) {
            if (Status == 'success') {
                $(xData.responseXML).find("Field[DisplayName='" + categoryFieldDisplayName + "'] CHOICE").each(function () {
                    // $("#usernames").append("<div class=\"dataview-choice-option\">" + $(this).text() + "</div>");
                    //  selectlist.append($('<option></option>').val($(this).text()).html(text));
                    // $("#ddlcategory").append(new Option($(this).text(), $(this).text())); bgcolors
                    $("#divcategory").append("<div class='clscheckbox' style='color:" + bgcolors[colorCounter] + "' id='div" +
$(this).text().replace(/ /g,'') + "'><input class='clscategory' type='checkbox' id='" + $(this).text() + "' value='" + $(this).text() +
"'/>" + $(this).text() + "</div>");
                    colorCounter++;
                });
            }
        }
       ///////////////////////////////////////
  //////////////Retrieve list items for the selected category
        function retrieveListItems(categoryVal) {
            var clientContext = new SP.ClientContext.get_current(); //(siteUrl);
            var oList = clientContext.get_web().get_lists().getByTitle('Calendar');
            var camlQuery = new SP.CamlQuery();
            // var categoryVal = $("#ddlcategory").val();
            //camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="' + categoryFieldInternalName + '"/><Value Type="Text">' +
categoryVal + '</Value></Eq></Where></Query><RowLimit>10</RowLimit></View>');
            //camlQuery.set_viewXml('<View><Query><Where><In><FieldRef Name="' + categoryFieldInternalName + '"/><Values>' + categoryVal
+ '</Values></In></Where></Query><RowLimit>10</RowLimit></View>');
            camlQuery.set_viewXml('<View><Query><Where><And><In><FieldRef Name="' + categoryFieldInternalName + '"/><Values>' +
categoryVal + '</Values></In><Contains><FieldRef Name="Year" />'+
            '<Value Type="Text">'+$('#ddlyear').val()+'</Value></Contains></And></Where></Query><RowLimit>10</RowLimit></View>' +
            '<ViewFields><FieldRef Name=\'EventDate\'/><FieldRef Name=\'EndDate\'/><FieldRef Name=\'fAllDayEvent\'/><FieldRef Name=
\'Title\'/><FieldRef Name=\'ID\'/><FieldRef Name="ID"/>'+
            '<FieldRef Name="LinkFilenameNoMenu"/><FieldRef Name="Created"/><FieldRef Name='+categoryFieldInternalName
+'/></ViewFields>');
            this.collListItem = oList.getItems(camlQuery);
            clientContext.load(collListItem);
            catColor = bgcolors[colorCounter];
            clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
            colorCounter++;
        }
  ///////////////////////////////////
        function onQuerySucceeded(sender, args) {
            var listItemInfo = '';
            var listItemEnumerator = collListItem.getEnumerator();
            var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
               "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                var StartDate = new Date(oListItem.get_item('EventDate'));
                var EndDate = new Date(oListItem.get_item('EndDate'));
                var alldayevent=oListItem.get_item('fAllDayEvent');             
                var listUrl=window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl +
'/CoC/SPCoC/lists/calendar/Dispform.aspx?ID='+oListItem.get_item('ID');
                var category = oListItem.get_item(categoryFieldInternalName);
                var  myTZO = 480;//Convert to Singapore time zone
                if(alldayevent==true)
                {
                 myTZO = 0;
                }
    StartDate =new Date(StartDate.getTime() + (60000*(StartDate.getTimezoneOffset()+myTZO)));//Convert to
Singapore time zone
    EndDate =new Date(EndDate.getTime() + (60000*(EndDate.getTimezoneOffset()+myTZO)));//Convert to Singapore
time zone
                var categoryColor=$("#div" + $.trim(category).replace(/ /g, '')).css("color");
           
                var dateDiff=daydiff(StartDate,EndDate);//Get date difference
                for (i = 1; i <= dateDiff; i++) {
                  if (StartDate.getFullYear()==$("#ddlyear").val())
                  {
       if(StartDate.getDay()!=6 && StartDate.getDay()!=0){
                       $("#" + months[StartDate.getMonth()] + "_" + StartDate.getDate()).append("<a target='_blank'
href='"+listUrl+"'><div style='background-color:" + categoryColor + ";width:10px;float:left;cursor:pointer;margin-left: 2px;' title='" +
category + "'>&nbsp</div></a>");
                      }
        StartDate.setDate(StartDate.getDate() + 1);
      }
                }
               
            }

        }

        function onQueryFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
  function daydiff(first, second) {
      return Math.round((second-first)/(1000*60*60*24));
  }
        $("#btnselect").click(function () {        
            var selectedCatgrs = '';
            $('input:checkbox.clscategory').each(function () {
                var sThisVal = (this.checked ? $(this).val() : "");
                if (sThisVal != "") {
                    selectedCatgrs = '<Value Type="Text">' + sThisVal + '</Value>' + selectedCatgrs; //sThisVal + ";" + selectedCatgrs;
                }
            });
            retrieveListItems(selectedCatgrs);
            $(".calyear").remove();
            strBody = '';
            var year = $("#ddlyear").val()
            var FebNumberOfDays = 0;
            today = new Date("January 1, " + year)
            start_day = today.getDay() + 1
            strBody += "<TABLE BORDER=1 style='padding:0px;' class='calyear'><TR><TD align=center colspan=11><B>Year Calendar</TD><TD
align=right><B>" + year + "</TD></TR><TR>";

            fill_table("Jan", 31, year)
            //Determing if February (28,or 29) 
            if ((year % 100 != 0) && (year % 4 == 0) || (year % 400 == 0)) {
                FebNumberOfDays = 29;
            } else {
                FebNumberOfDays = 28;
            }
            fill_table("Feb", FebNumberOfDays)
            fill_table("Mar", 31)
            fill_table("Apr", 30)
            fill_table("May", 31)
            fill_table("Jun", 30)
            fill_table("Jul", 31)
            fill_table("Aug", 31)
            fill_table("Sep", 30)
            fill_table("Oct", 31)
            fill_table("Nov", 30)
            fill_table("Dec", 31)
            strBody += "</TR></TABLE>";
            $("#dvparent").append(strBody);
            //  FillData();
        });
    });
    function day_title(day_name,dayofweek,year,month) {
        if (dayofweek == "Sa" || dayofweek == "Su") {
            strBody += "<TR class='weekend'><TD ALIGN=right>" + day_name + "</TD><TD>" + dayofweek + "</TD><TD width='60px' id='" + month
+ '_' + day_name + "'></TD></TR>";
        }
        else {
            strBody +=  "<TR><TD ALIGN=right >" + day_name + "</TD><TD>" + dayofweek + "</TD><TD width='60px' id='" + month + '_' +
day_name + "'></TD></TR>";
        }
    }
    function fill_table(month, month_length,year) {
        day = 1
        strBody += "<TD style='vertical-align: top;'><TABLE class='tblmonth' ID=" + month + "><TR>";
        strBody += "<TD COLSPAN=3 ALIGN=center width='120px'><B>" + month + "</TD><TR>";
    
        for (var i = start_day; i < 8; i++) {
          
            day_title(day, getDayName(start_day),year,month);
            day++;
            if (start_day == 7) {
                start_day = 1;
            }
            else {
                start_day++;
            }
        }
        strBody += "<TR>";
        while (day <= month_length) {
            for (var i = 1; i <= 7 && day <= month_length; i++) {
                              
                if (start_day > 7) {
                    start_day = 1;
                }
                day_title(day, getDayName(start_day),year,month);
                day++
                start_day++
                //else {
                  //  start_day++;
                //}
            }
            strBody += "</TR><TR>";
            start_day = i;
        }
        strBody += "</TABLE></TD>";
    }
    function getDayName(dayVal) {
        switch (dayVal) {
            case 1:
                dayname = "Su";
                break;
            case 2:
                dayname = "Mo";
                break;
            case 3:
                dayname = "Tu";
                break;
            case 4:
                dayname = "We";
                break;
            case 5:
                dayname = "Th";
                break;
            case 6:
                dayname = "Fr";
                break;
            case 7:
                dayname = "Sa";
                break;
            default:
                dayname = "NA";
        }
        return dayname;
    }
    function FillData() {
        $("#Jan_4").append("<div style='background-color:blue;width:10px;float:left;cursor:pointer;' title='Cat1'>&nbsp</div>");
        $("#Jan_5").append("<div style='background-color:blue;width:10px;float:left;cursor:pointer;' title='Cat1'>&nbsp</div>");
        $("#Jan_6").append("<div style='background-color:blue;width:10px;float:left;cursor:pointer;' title='Cat1'>&nbsp</div>");
        $("#Jan_7").append("<div style='background-color:blue;width:10px;float:left;cursor:pointer;' title='Cat1'>&nbsp</div>");
        $("#Jan_4").append("<div style='background-color:green;width:10px;float:left;cursor:pointer;' title='Cat2'>&nbsp</div>");
        $("#Jan_5").append("<div style='background-color:green;width:10px;float:left;cursor:pointer;' title='Cat2'>&nbsp</div>");
        $("#Jan_6").append("<div style='background-color:green;width:10px;float:left;cursor:pointer;' title='Cat2'>&nbsp</div>");
        $("#Jan_7").append("<div style='background-color:green;width:10px;float:left;cursor:pointer;' title='Cat2'>&nbsp</div>");
        $("#Jan_8").append("<div style='background-color:green;width:10px;float:left;cursor:pointer;' title='Cat2'>&nbsp</div>");
        $("#Febr_4").append("<div style='background-color:green;width:10px;float:left;cursor:pointer;' title='Cat2'>&nbsp</div>");
        $("#Febr_5").append("<div style='background-color:green;width:10px;float:left;cursor:pointer;' title='Cat2'>&nbsp</div>");
        $("#Febr_6").append("<div style='background-color:green;width:10px;float:left;cursor:pointer;' title='Cat2'>&nbsp</div>");
        $("#Febr_7").append("<div style='background-color:green;width:10px;float:left;cursor:pointer;' title='Cat2'>&nbsp</div>");
    }
 
// End -->
</script>
</head>
<body>
<table style="border: 1px solid lightblue; margin-bottom: 5px;"><tr><td colspan="2" style="font-weight:bold">Year:
<select id='ddlyear'>
<option value='2015'>2015</option>
<option value='2016'>2016</option>
<option value='2017'>2017</option>
<option value='2018'>2018</option>
</select></td></tr>
<tr><td style="font-weight:bold"><div style="float:left">Team Members:</div><div id='divcategory'
style="float:left"></div></td><td><input type="button" id="btnselect" value='Display'/></td></tr></table>
<div id="dvparent"></div>

</body>
</html>




No comments:

Post a Comment