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:

//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

function SetGroupOnly(fieldName)
//make sure there is a control for that field on the page
    //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)

No comments: