Solved

SharePoint Online Adding A People Picker to Search

Posted on 2016-11-16
14
23 Views
Last Modified: 2016-11-16
I have a web page and need to add the people picker search to the page and use the person/people selected for subsequent on page processing (adding to a list, searching a list etc.).

Any ideas about this would be great.

Thanks.
0
Comment
Question by:hbash
  • 8
  • 6
14 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 41890352
the only thing you need is to retrieve the user id when selected.
check this page but i'm pretty sure you know it :
https://msdn.microsoft.com/en-US/library/office/jj713593.aspx

especially this part : https://msdn.microsoft.com/en-US/library/office/jj713593.aspx#code-snippet-2
check the function GetUserId
0
 
LVL 1

Author Comment

by:hbash
ID: 41890421
I have tried the first URL code and I think that the second one will have the same problem.  In the init,  the statement
  this.SPClientPeoplePicker_InitStandaloneControlWrapperl(...) fails and the   this.SPClientPeoplePicker_InitStandaloneControlWrapper object is not defined.

I have tried adding references to other modules, but no luck.  I will include my code which I paste into a script editor:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ></script>
<script type="text/javascript" src="/_layouts/15/1033/strings.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>

<div>
	<p id="message">
		<!-- The following content will be replaced with the user name when you run the app - see App.js -->
		initializing...
	</p>
</div>
<div id="peoplePickerDiv"></div>
<div>
	<br />
	<input type="button" value="Get User Info" onclick="getUserInfo()"></input>
	<br />
	<h1>User info:</h1>
	<p id="resolvedUsers"></p>
	<h1>User keys:</h1>
    <p id="userKeys"></p>
</div>	


<script type="text/javascript">
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {


    getUserName();

    initializePeoplePicker('peoplePickerDiv');
});

// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}

// Render and initialize the client-side People Picker.
function initializePeoplePicker(peoplePickerElementId) {

    // Create a schema to store picker properties, and set the properties.
    var schema = {};
    schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
    schema['SearchPrincipalSource'] = 15;
    schema['ResolvePrincipalSource'] = 15;
    schema['AllowMultipleValues'] = true;
    schema['MaximumEntitySuggestions'] = 50;
    schema['Width'] = '280px';

    // Render and initialize the picker.
    // Pass the ID of the DOM element that contains the picker, an array of initial
    // PickerEntity objects to set the picker value, and a schema that defines
    // picker properties.

this.SPClientPeoplePicker.ShowUserPresence = false;

    this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}

// Query the picker for user information.
function getUserInfo() {

    // Get the people picker object from the page.
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;

    // Get information about all users.
    var users = peoplePicker.GetAllUserInfo();
    var userInfo = '';
    for (var i = 0; i < users.length; i++) {
        var user = users[i];
        for (var userProperty in user) {
            userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
        }
    }
    $('#resolvedUsers').html(userInfo);

    // Get user keys.
    var keys = peoplePicker.GetAllUserKeys();
    $('#userKeys').html(keys);
}

</script>

Open in new window

0
 
LVL 1

Author Comment

by:hbash
ID: 41890462
I have found an interesting URL/plugin which may work.  However,  when I add it to a script editor,  I don't see any place to type in a user name.

Here is the URL:
Link to jQuery Plugin

Here is the code I used in the Script Editor:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ></script>
<script type="text/javascript" src="https://someDomain.sharepoint.com/sites/Montage%20IT%20Development/SomeSite/BlogBox/BlogStyleLibrary/sppeoplePicker.min.js"</script>

<script type="text/javascript">
    $(document).ready(function () {
                $("#peoplePickerDiv").spPeoplePicker();
                $("#anotherPeoplePickerDiv").spPeoplePicker();
 
             
            $("#pp1").click(function(){
                alert($("#peoplePickerDiv").getUserInfo());
                return false;
            });
            $("#pp2").click(function(){
                alert($("#anotherPeoplePickerDiv").getUserInfo());
                return false;
            });
 
    });
     
</script>

<table class="spPeoplePickerTable" width="50%" cellpadding="10" cellspacing="1">
    <tr>
        <td>People Picker 1: </td>
        <td><div id="peoplePickerDiv"></div></td>
        <td><button id="pp1">Show</button></td>
    </tr>
    <tr>
        <td>People Picker 2:</td>
        <td><div id="anotherPeoplePickerDiv"></div></td>
        <td><button id="pp2">Show</button></td>
    </tr>
 
</table>

Open in new window

0
 
LVL 1

Author Comment

by:hbash
ID: 41890494
Found another interesting URL...

SPWidgets
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41890520
hold on !!! ^^
let's try to fix the common one, don't get discouraged :D
I see you put only  clientpeoplepicker.js and miss clientforms.js and autofill.js
0
 
LVL 1

Author Comment

by:hbash
ID: 41890524
Ok.  If you can please provide modified version of my snippet.
Thanks.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41890530
line 2, I see :
<script type="text/javascript" src="https://someDomain.sharepoint.com/sites/Montage%20IT%20Development/SomeSite/BlogBox/BlogStyleLibrary/sppeoplePicker.min.js" <----- miss something here

not close, is this really what you have ?
<script type="text/javascript" src="https://someDomain.sharepoint.com/sites/Montage%20IT%20Development/SomeSite/BlogBox/BlogStyleLibrary/sppeoplePicker.min.js"></script>
0
Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

 
LVL 82

Expert Comment

by:leakim971
ID: 41890538
on my Sharepoint site, I ran your code and I don't have issue with the two objects after adding the three "js" files
as you can see on the screen copy, this.SPClientPeoplePicker and this.SPClientPeoplePicker_InitStandaloneControlWrapper are well defined
look fine, no error
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 41890540
check here for the "include" :
https://msdn.microsoft.com/en-us/library/office/jj713593.aspx#bk_example

    <SharePoint:ScriptLink name="clientforms.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink name="clientpeoplepicker.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink name="autofill.js" runat="server" LoadAfterUI="true" Localizable="false" />

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 41890543
here the second note : https://msdn.microsoft.com/en-us/library/office/jj713593(v=office.15).aspx
The picker and its functionality are defined in the clientforms.js, clientpeoplepicker.js, and autofill.js script files, which are located in the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS folder on the server.
0
 
LVL 1

Author Comment

by:hbash
ID: 41890756
This is the exact code that I pasted into the "Script Editor" Web Part:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ></script>

<script type="text/javascript">
// Run your custom code when the DOM is ready.
$(document).ready(function () {

    // Specify the unique ID of the DOM element where the
    // picker will render.
    initializePeoplePicker('peoplePickerDiv');
});

// Render and initialize the client-side People Picker.
function initializePeoplePicker(peoplePickerElementId) {

    // Create a schema to store picker properties, and set the properties.
    var schema = {};
    schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
    schema['SearchPrincipalSource'] = 15;
    schema['ResolvePrincipalSource'] = 15;
    schema['AllowMultipleValues'] = true;
    schema['MaximumEntitySuggestions'] = 50;
    schema['Width'] = '280px';

    // Render and initialize the picker. 
    // Pass the ID of the DOM element that contains the picker, an array of initial
    // PickerEntity objects to set the picker value, and a schema that defines
    // picker properties.
    this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}

// Query the picker for user information.
function getUserInfo() {

    // Get the people picker object from the page.
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;

    // Get information about all users.
    var users = peoplePicker.GetAllUserInfo();
    var userInfo = '';
    for (var i = 0; i < users.length; i++) {
        var user = users[i];
        for (var userProperty in user) { 
            userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
        }
    }
    $('#resolvedUsers').html(userInfo);

    // Get user keys.
    var keys = peoplePicker.GetAllUserKeys();
    $('#userKeys').html(keys);

    // Get the first user's ID by using the login name.
    getUserId(users[0].Key);
}

// Get the user ID.
function getUserId(loginName) {
    var context = new SP.ClientContext.get_current();
    this.user = context.get_web().ensureUser(loginName);
    context.load(this.user);
    context.executeQueryAsync(
         Function.createDelegate(null, ensureUserSuccess), 
         Function.createDelegate(null, onFail)
    );
}

function ensureUserSuccess() {
    $('#userId').html(this.user.get_id());
}

function onFail(sender, args) {
    alert('Query failed. Error: ' + args.get_message());
}

</script>

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
    <SharePoint:ScriptLink name="clienttemplates.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink name="clientforms.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink name="clientpeoplepicker.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink name="autofill.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink name="sp.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink name="sp.runtime.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <SharePoint:ScriptLink name="sp.core.js" runat="server" LoadAfterUI="true" Localizable="false" />
    <div id="peoplePickerDiv"></div>
    <div>
        <br/>
        <input type="button" value="Get User Info" onclick="getUserInfo()"></input>
        <br/>
        <h1>User info:</h1>
        <p id="resolvedUsers"></p>
        <h1>User keys:</h1>
        <p id="userKeys"></p> 
        <h1>User ID:</h1>
        <p id="userId"></p>
    </div>
</asp:Content>

Open in new window


It had the same problem that this.SPClientPeoplePicker_InitStandaloneControlWrapper is undefined.

Here is a screen capture of the debug:
Undefined
0
 
LVL 1

Author Comment

by:hbash
ID: 41890774
I'm not sure about adding these references as shown to a Script Editor Web Part.  It looks more like what one would add to an aspx page.  Correct me if I'm wrong here.  But please note, that I need this to be added to the Script Editor Web Part.
0
 
LVL 1

Author Comment

by:hbash
ID: 41890789
Just got it to work by adding the references to the top of the snippets:

  <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js" type="text/javascript"></script>

    <script type="text/javascript" src="/_layouts/15/clienttemplates.js"></script>
    <script type="text/javascript" src="/_layouts/15/clientforms.js"></script>
    <script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>
    <script type="text/javascript" src="/_layouts/15/autofill.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.core.js"></script>
1
 
LVL 1

Author Comment

by:hbash
ID: 41890802
Now how do I use this to turn a textbox into a people picker?  It looks like it needs to a div and that the initialize makes it behave like a textbox that is a people picker.   I have a form with a textbox that is part of a bootstrap form and somehow I will need to change the people textbox to this div/people picker and then query it to get back the account(s) that are resolved within.

And once that is understood/built,  how can I get back the user account?  it is displaying lastname, firstname in the div/pp.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now