How to Set People picker is the current logged-on user value In SharePoint 2010/SharePoint 2007

I believe many of my friends have encountered one requirement of setting the current logged-on user value to one People field type and has given a solution, so this is nothing new, the algorithm is also relatively redundant, only operator in the blog For knowledge backup.

In the upper right corner of the screen has a welcome control, display as "Welcome, login user name ", our code is to take the user name taken out, then take to the field corresponding PeoplePicker DIV, innerHTML property to be worth calling to set.

How to Set People picker is the current logged-on user value In SharePoint 2010/SharePoint 2007

How to Set People picker is the current logged-on user value In SharePoint 2010/SharePoint 2007

The first step to obtain logged on user, through the Welcome to find:

function getCurrentUser() 
{
var tags = document.getElementsByTagName('a');
for (var i=0; i < tags.length; i++)
{
if(tags[i].innerText.substr(0,7) == 'Welcome')
{
return tags[i].innerText.substr(8,tags[i].innerText.length);
}
}
}







The second step, find the corresponding fields PeoplePicker DIV, inside back layer by layer, the algorithm is not good, will continue to cycle after the last break, although no effect on the final result, but not a good algorithm, interested friends Find a good algorithm or algorithms can be found through the JQuery welcome to share!




function getPickerInputElement(fieldsInternalName) 
{
var result = "";
var divs = document.getElementsByTagName("DIV");
for(var i=0; i < divs.length ; i++)
{

if(divs[i].id=="WebPartWPQ2")
{
var tds = divs[i].getElementsByTagName("TD");
for(var j=0; j < tds.length; j++)
{
var cellHTML = tds[j].innerHTML;
if(cellHTML.indexOf('FieldInternalName="' + fieldsInternalName + '"') >= 0)
{
var innerDivs = tds[j].getElementsByTagName("DIV");
for(var k=0; k < innerDivs .length; k++)
{
if(innerDivs[k].id.indexOf("UserField_upLevelDiv") > 0)
{
result = innerDivs[k];
break;
}
}
}
}
}
}
return result;
}







The third step is to set the value, we adopted a method called fillPeoplePickerWithCurrentUser to be set, call the SharePoint library method _spBodyOnLoadFunctionNames, to ensure the method will be executed after the page finished loading the content.




_spBodyOnLoadFunctionNames.push("fillPeoplePickerWithCurrentUser");

function fillPeoplePickerWithCurrentUser()
{
var currentUser = getCurrentUser();
if(currentUser != null)
{
var pp = getPickerInputElement(“SetMe”);
if(pp != null)
pp.innerHTML = currentUser;
}
}







Description:

This method is not in the Firefox browser for debugging.