Monday 5 January 2015

Setting Default Value to the Person/Group Column in New/Edit form



By using JavaScript the default value for a person or group column can be set. The below are the steps
(i) Add content Webpart
(ii)Inside that put the following script
(This script will fetch the current username and display it in the people picker which is mentioned in the script)
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(GetUserLoginName, "sp.js");
 var context = null;
    var web = null;
    var currentUser = null;
    var currentUserId=''
function GetUserLoginName() {
 context = new SP.ClientContext.get_current();
        web = context.get_web();
        currentUser = web.get_currentUser();
        currentUser.retrieve();
        context.load(web);
        context.executeQueryAsync(onSuccessMethod, onFaiureMethodl);
}
function onSuccessMethod(sender, args) {
        var userObject = web.get_currentUser();
           AddCurrentUserToPP(userObject.get_title());
    }
  
    function onFaiureMethodl(sender, args) {
        alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
    }

function AddCurrentUserToPP(LoginName)
{
var pickerNo = 1;
var pp = getPickerImputElement(pickerNo);
if(pp != null)
{
pp.innerHTML = LoginName;
}
}

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;
}</script>
(iii) Stop Editing

1 comment:

  1. How can this javascript be if you want to set any user, not the current one into a specific people picker column

    ReplyDelete