Auto fill SharePoint person field with default logged in user

Addd a Content Editor Web Part to the New Form page. To do this, add the following to the end of the new form url:

?ToolPaneView=2

You will then be able to add web parts to the page. Add the Content Editor Web Part to the page, then Edit Source and add the script. Set the web part to be hidden.

The script code:

<script type=”text/javascript”>
_spBodyOnLoadFunctionNames.push(“fillDefaultValues”);

function fillDefaultValues()
{

fillPeoplePickerWithCurrentUser(‘Submitted_x0020_By’);

}

function fillPeoplePickerWithCurrentUser(pickerName)
{

//get the current user from the welcome menu
var currentUser = getCurrentUser();

//check to see that we’ve got it
if(currentUser != null)
{

//get the people pickers input div
var pp = getPickerInputElement(pickerName);
//set it to the current user if we’ve found it
if(pp != null)

pp.innerHTML = currentUser;

}

}

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);

}

}

}

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;

}
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami