Wednesday, June 12, 2019

Restricting a User Picker field to only selecting SharePoint groups

 After a lot of research, I couldn't find the answer, so I wrote one myself.
To change a person field in sharepoint that is configured to allow "users and groups" to only allow groups, you need to inject code that changes the picker settings after the page is loaded.

Code below:



$(document).ready(function(){
//wait for the initialisation of the sharepoint script 

  SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
//call our special function with the field's internal name
    SetGroupOnly("myfieldinternalname");
  });
});

function SetGroupOnly(fieldName)
{
//make sure there is a control for that field on the page
  if($("div[id^='"+fieldName+"_']").length>0)
  {
    //wait for the initialisation of the control to finish
    WaitForControl("div[id^='"+fieldName+"_'][id$='$ClientPeoplePicker']", function(){
//get the people picker control object
      var peoplepicker = SPClientPeoplePicker.SPClientPeoplePickerDict[$("div[id^='"+fieldName+"_'][id$='$ClientPeoplePicker']").attr("id")];
//set the type to SPGroup
      peoplepicker.PrincipalAccountType = "SPGroup";
      peoplepicker.PrincipalAccountTypeEnum = 8;
      peoplepicker.ResolvePrincipalSource = 15;
      peoplepicker.SearchPrincipalSource = 15;
    });
  }
}



function WaitForControl(controlSelector, returnFunction)
{
  if($(controlSelector).length>0)
    returnFunction();
  else
    setTimeout(function(){
      WaitForControl(controlSelector,returnFunction)},50);    
}