Tuesday, July 9, 2013

SharePoint Person or Group Field – Populate with Current User as the Default Value

I’m having a user type field in one of my publishing page layouts and I wanted to default it to current user. So when an author creating a page, user field will automatically populated with the current user. If author decided to change the value and set it to another user, new value will be retained.


I found this post: Set SharePoint PeoplePicker Fieldmark 2 in Andy Bonner's Blog, where the provided script is working fine in SharePoint 2010, but not in SharePoint 2013.

Here is the slightly modified version of the script for SharePoint 2013:

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

function fillDefaultValues() {
  fillPeoplePickerWithCurrentUser(1);
  fillPeoplePickerWithCurrentUser(2);
}

function fillPeoplePickerWithCurrentUser(pickerNo) {
  var currentUser = getCurrentUser();
  if (currentUser != null) {
    var pp = getPickerImputElement(pickerNo);
    if (pp != null) {
      if (pp.innerHTML == '') {
        pp.innerHTML = currentUser;
      }
    }
  }
}

function getPickerImputElement(pickerNo) {
  var result = '';
  var divs = document.getElementsByTagName('DIV');
  var j = 0;
  for (var i = 0; i < divs.length; i++) {
    if (divs[i].id.indexOf('UserField_upLevelDiv') > 0) {
      j++;
      if (j == pickerNo) {
        result = divs[i];
        break;
      }
    }
  }
    return result;
}

function getCurrentUser() {
    var tags = document.getElementsByTagName('a');
    for (var i = 0; i < tags.length; i++) {
        if (tags[i].id == 'zz4_Menu') {
            var userName = tags[i].innerHTML;
            userName = userName.substr(0, userName.indexOf("<"))
            return userName;
        }
    }
}
</script>

2 comments:

Unknown said...

Can i use this code by putting it in content editor webpart for populating the current user in newForm.aspx???

Unknown said...

View this add-on(SharePoint Default Value Add-On), which inject a "default value" section into "Create Column" dialog.

Set "Current User" (User who is adding item) as default value.