Setting People Picker columns default value as Current User in SharePoint 2010 using JavaScript

This blog post talks about how to set the default value of the People Picker field as the logged in current user in the NewForm.asxp / EditForm.aspx in SharePoint 2010. There are a lot of various techniques using CSOM and Add-On applications available on the internet to achieve this task. This post however talks about a brute force method of using the logged in users name to be filled in the People picker column using JQuery & JavaScript by editing it in SharePoint Designer.

Uses JavaScript, JQuery & CSS of the default master page in SharePoint 2010

Approach

The default master page of SharePoint 2010 uses certain classes and id’s to define its styles. These element selectors (classes & ids) are used to extract the name of the logged in user from the login module of the Master page as seen in the image below and filled in the people picker field using Javascript.

This activity is coded by overriding the pageLoad() function of the SharePoint page in JavaScript.

LoginName

Code

Edit the desired form in “Advanced Mode” using SharePoint designer and write the code as below inside the PlaceHolderMain of the form.

Since this code uses JQuery, refer the JQuery library in your code as seen below. The JQuery library is stored in my “Shared Documents” library of the same site

<script src="../../Shared Documents/jquery-1.11.1.js"></script>

Code below does the real job on page load.

function pageLoad()
{
	fillCurrentUserInPPColumn("AssignedTo");  //"AssignedTo" is a people picker column
}
function fillCurrentUserInPPColumn(colName)
{
	var name = $("#RibbonContainer-TabRowRight").find(".s4-trc-container-menu").find(".ms-menu-a").children("span").text()

	$(".ms-standardheader").filter(function(){
		return $(this).children("nobr").text()==colName;
	}).each(function(){
		$(this).parent().next().find("textarea").prev().text(name);
	});
}

This code will not work if the People Picker column is  mandatory as it will introduce an additional <span> element for the ‘*’ symbol. You can remove the <span> element from the <nobr> element and have it outside the <nobr> element.

Cheers!!

Happy coding 🙂

Expand/Collapse all groups of a Grouped SharePoint list using jQuery

It was required to build a functionality to expand / collapse all groups of a grouped SharePoint list in a list view. Since there is no OOB feature in SharePoint to have this functionality, a jQuery script was written to bring about this effect.

Let us consider a “Tasks” list grouped by “Status’ column as seen below

groupedSPList

groupedSPList2

A jQuery script can be invoked on a click event of some HTML element that will simulate a click on the “Status” as shown in the image above.

A simple HTML Button can be added using a Content Editor webpart along with the jQuery script written below.

<button id="btnExpand" type="button">Expand / Collapse</button>
$(document).ready(function(){
    $("#btnExpand").click(function(){
        $(".ms-listviewtable").find("tr[id*='group']").each(function(){
            $(this).find("a[href='javascript:']").click();
        });
    });
});

Also, dont forget to include the jQuery library reference in your code as below

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Happy coding 🙂

How to create a PDF viewer in SharePoint 2010

How to create a PDF viewer in SharePoint 2010

Dougieflash's Weblog

How to Create a PDF Viewer in SharePoint 2010

Creating a PDFViewer without creating a web part in SharePoint 2010 is possible simply by using a little Javascript. The object of this article is to explain how to display different embedded PDFs in a SharePoint page and using a drop down list to change the PDF. Want to go full screen? Also doable. To begin this tutorial start by adding a Document library that contain several .pdf files.

pdfViewer1

Next, edit the current View of the Web part and display only the column name (linked to document).

pdfViewer3

Edit the filter section of the document library to filter the Name field that contains “.PDF”

pdfViewer2

Save the view.

Open any text editor and copy the Javascript below:

For debugging purposes, comment the line that starts with “x[i].parentNode.” (just add two slashes: “// x[i].parentNode.”)

– this line hides the library web part. Save the…

View original post 333 more words

Adding a asmx WebService to the SharePoint solution in Visual Studio

This post illustrates how to add a asmx WebService to a SharePoint solution in Visual Studio.

How *.asmx WebService works?

When we develop an asmx WebService in a normal ASP.Net web application, it will have an *.asmx file that will contain information of the library and the class name that the WebService refers to. The code for the WebService is written in a separate .cs class file with appropriate attributes for the webmethods. On deployment, the asmx file resides on the file system and the class files encapsulates into a *.dll library and get installed in GAC

ASMX WebService for SharePoint solution

We can package the *.asmx WebService in a SharePoint solution by adding the *.asmx file into the mapped layouts folder that refers to some class file in the solution. Refer screenshots below to successfully add the WebService on your SharePoint solution

Continue reading

Imposing maxlength in textarea for limiting number of characters

A textarea tag in HTML traditionally does not have a “maxlength” attribute as we have it in the text type input tag. Hence it can accept any number of characters. In order to implement maxlength for textarea elements, employ the JavaScript below and use this script as illustrated in the HTML mark up below.

JavaScript

function ismaxlength(obj) 
{
    var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
    if (obj.getAttribute && obj.value.length > mlength)
        obj.value = obj.value.substring(0, mlength);
}

HTML

<textarea id="txtTextArea" maxlength="150"onkeyup="return ismaxlength(this)" rows="3" cols="30">
Text comes here
</textarea>

Optimizing textbox to accept date value in a valid format using JavaScript

Textboxes are widely used for accepting date values in forms. Attaching JQuery calendars to these textboxes is easy and convenient way of accomplishing the task, however, these JQuery calendars require the user to use the mouse to furnish the details.

A requirement was raised that the date value must be allowed to be entered via keyboard along with the JQuery calendar. Also, it should be taken care that the date is entered in a valid date format. Hence this prompted me to write this code in JavaScript.

JavaScript

function preActuation(evt)
{
	var charCode = getCharCode(evt);
	var element = document.activeElement;
	if(element.value=="")
	{
		element.value=element.getAttribute("format");
		setCaretPos(element, 0);
	}
	var selStart = parseInt(getCaretPos(element));
	if(element.value.charAt(selStart)==element.getAttribute("dateseparator"))
		return false;
	if((charCode>=35 && charCode<=40)||(charCode>=96 && charCode<=105))
		return true;
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	if(charCode==8)
		return false;
}
function dateEntryActuation(evt)
{
	var charCode = getCharCode(evt);
	var element = document.activeElement;
	var selectionStart = parseInt(getCaretPos(element));
	var charTyped = String.fromCharCode(charCode);
	var text = element.value;
	text = text.substr(0,selectionStart)+charTyped+text.substr(selectionStart+1,text.length-selectionStart-1);
	var dateText = text.replace(new RegExp('_', 'g'),"0").replace(new RegExp('d', 'g'),"0").replace(new RegExp('M','g'),"0").replace(new RegExp('y', 'g'),"0");
	var day = parseInt(dateText.substr(element.getAttribute("format").indexOf("d"),2));
	var month = parseInt(dateText.substr(element.getAttribute("format").indexOf("M"),2));
	if((day>=0 && day<32) && (month>=0 && month<13))
		element.value = text;
	else
		return false;
	setCaretPos(element, selectionStart+1);
	return false;
}
function endActuation(evt)
{
	var charCode = getCharCode(evt);
	var element = document.activeElement;
	var selectionStart = getCaretPos(element);
	if(element.value.length>10)
		element.value = element.value.substr(0,10);
	if(element.value.charAt(selectionStart)==element.getAttribute("dateseparator"))
		setCaretPos(element, selectionStart+1);
}

function getCaretPos(el)
{
	if (typeof el.selectionStart != "undefined")
		return el.selectionStart;
	else if (document.selection)
		return Math.abs(document.selection.createRange().moveStart("character", -1000000));
}
function setCaretPos(el, pos)
{
	if(el.setSelectionRange)
	{
        	el.focus();
	        el.setSelectionRange(pos,pos);
    	}
	else if (el.createTextRange)
	{
        	var range = el.createTextRange();
	        range.collapse(true);
        	range.moveEnd('character', pos);
	        range.moveStart('character', pos);
        	range.select();
    	}
}

function getCharCode(evt)
{
	var charCode;
	if (window.event)
		charCode = window.event.keyCode;   //if IE
	else
		charCode = evt.which; //if firefox
	return charCode;
}

HTML

The mark up below illustrates the input tag that is used to accept date value. The JavaScript shown above uses custom attributes to enable the date validation actuation.

<input id="txtDate" class="date" type="text" value="__/__/____" title="dd/MM/yyyy" format="dd/MM/yyyy" dateseparator="/" style="width:80px;" onkeydown="return preActuation(event)" onkeypress="return dateEntryActuation(event);" onkeyup="return endActuation(event);">

Integration with JQuery Datepicker

If you wish to use this validation along with the JQuery Datepicker control from http://jqueryui.com/datepicker/ you must include the code below in the pageLoad() method of the JavaScript. This is because the datepicker widget interferes with the JavaScript written above. Hence the textbox javascript event attributes must be added explicitly from the JavaScript using the pageLoad() method.

function pageLoad(sender, args) {
    if ("<%=Page.IsPostBack%>" == false){
        $(function () {
            $(".date").attr("value", "__/__/____");
        });
    }
    $(function () {
        $(".date").attr("format", "dd/MM/yyyy");
        $(".date").attr("dateseparator", "/");
        $(".date").attr("onkeydown", "return preActuation(event)");
        $(".date").attr("onkeypress", "return dateEntryActuation(event)");
        $(".date").attr("onkeyup", "return endActuation(event)");
        $(".date").datepicker({ dateFormat: "dd/mm/yy" });
    }
}

Happy coding!! 🙂