PrePopulate Sharepoint People Picker field with logged in user in list forms – Sharepoint 2007

There is this very common requirement to prepopulate sharepoint people picker field with logged in  user name in New and Edit forms of  sharepoint list. Below is something one can consider to achieve this –

Using Sharepoint designer, add the following javascript code in Newform.aspx or EditForm.aspx to Pre-populate the logged in user as a default in sharepoint people picker control in custom list. 

Just copy & paste the following javascript code in NewForm.aspx/EditForm.aspx of sharepoint list and replace [PeoplePickerControlName] in the code below with the internal name of people picker field in your custom list. The script below has used in built sharepoint javascript function _spBodyOnLoadFunctionNames.push which invokes “fillDefaultValues” function on page load of NewForm.aspx.

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

function fillDefaultValues()
{
    fillPeoplePickerWithCurrentUser(‘[PeoplePickerControlName]’);
}
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>

 

 

Trackbacks

Leave a Comment

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