使用 SharePoint 托管的 SharePoint 加载项中的客户端人员选取器控件Use the client-side People Picker control in SharePoint-hosted SharePoint Add-ins

重要

本主题假定你知道如何创建 SharePoint 托管的 SharePoint 加载项。This topic assumes that you know how to create a SharePoint-hosted SharePoint Add-in. 若要了解如何创建,请参阅开始创建 SharePoint 托管的 SharePoint 加载项To learn how to create one, see Get started creating SharePoint-hosted SharePoint Add-ins.

SharePoint 中的客户端人员选取器控件是什么?What is the client-side People Picker control in SharePoint?

使用客户端人员选取器控件,用户可以为组织中的人员、组和声明快速搜索和选择有效的用户帐户。The client-side People Picker control lets users quickly search for and select valid user accounts for people, groups, and claims in their organization. 选取器是 HTML 和 JavaScript 控件,提供跨浏览器支持。The picker is an HTML and JavaScript control that provides cross-browser support.

将选取器添加到加载项的操作非常简单:Adding the picker to your add-in is easy:

  1. 在标记中添加控件的容器元素和的控件的引用及其依赖项。In your markup, add a container element for the control and references for the control and its dependencies.

  2. 在脚本中调用 SPClientPeoplePicker_InitStandaloneControlWrapper 全局函数,以呈现和初始化选取器。In your script, call the SPClientPeoplePicker_InitStandaloneControlWrapper global function to render and initialize the picker.

选取器由 SPClientPeoplePicker 对象表示,它提供其他客户端控件可以用来从选取器获取信息或执行其他操作的方法。The picker is represented by the SPClientPeoplePicker object, which provides methods that other client-side controls can use to get information from the picker or to perform other operations. 可以使用 SPClientPeoplePicker 属性为选取器配置特定于控件的设置,例如,允许多个用户或指定缓存选项。You can use SPClientPeoplePicker properties to configure the picker with control-specific settings, such as allowing multiple users or specifying caching options.

此外,选取器还使用 Web 应用程序配置设置,例如,Active Directory 域服务参数或目标林。The picker also uses web application configuration settings such as Active Directory Domain Services parameters or targeted forests. (从 SPWebApplication.PeoplePickerSettings 属性)自动选取 Web 应用程序配置设置。Web application configuration settings are picked up automatically (from the SPWebApplication.PeoplePickerSettings property).

选取器由下列组件组成:The picker has the following components:

  • 用于输入用户、组和声明的名称的输入文本框。An input text box to enter names for users, groups, and claims.
  • 范围控件,用于显示解析的用户、组和声明的名称。A span control that shows the names of resolved users, groups, and claims.
  • 使用匹配的查询结果自动填充下拉框的隐藏的 div 元素。A hidden div element that autofills a drop-down box with matching query results.
  • 自动填充控件。An autofill control.

备注

选取器及其功能在 clientforms.jsclientpeoplepicker.jsautofill.js 脚本文件中定义,这些文件位于服务器上的 %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS 文件夹中。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.

设置在 SharePoint 加载项中使用客户端人员选取器控件的开发环境的先决条件Prerequisites for setting up your development environment to use the client-side People Picker control in a SharePoint Add-in

本文假定你通过在 Office 365 开发人员网站上使用 Napa 来创建 SharePoint 加载项。This article assumes that you create the SharePoint Add-in by using Napa on an Office 365 developer site. 如果使用的是此开发环境,则你已满足先决条件。If you're using this development environment, you've already met the prerequisites.

备注

若要了解如何注册开发人员网站,并开始使用 Napa,请参阅在 Office 365 上设置 SharePoint 加载项开发环境To find out how to sign up for a developer site and start using Napa, see Set up a development environment for SharePoint Add-ins on Office 365.

如果不打算在开发人员网站上使用 Napa,需要满足以下条件:If you're not using Napa on a developer site, you need the following:

  • 具有至少一个目标用户的 SharePointSharePoint with at least one target user
  • Visual Studio 2008 或 Visual Studio 2013Visual Studio 2012 or Visual Studio 2013
  • Visual Studio 2013 的 Office 开发人员工具Office Developer Tools for Visual Studio 2013

备注

有关如何设置符合你的需求的开发环境的指南,请参阅 SharePoint 加载项For guidance about how to set up a development environment that fits your needs, see SharePoint Add-ins.

以下部分介绍将该选取器添加到你的加载项中,然后从其他客户端控件获取其用户信息的概要步骤。The following sections describe the high-level steps for adding the picker to your add-in and then getting its user information from another client-side control. 要查看相应代码,请参阅代码示例:使用客户端人员选取器For the corresponding code, see Code example: Using the client-side People Picker.

可以在 SharePoint 托管的 SharePoint 加载项中使用客户端人员选取器控件,但不能在提供程序托管的加载项中使用。You can use the client-side People Picker control in SharePoint-hosted SharePoint Add-ins, but not in provider-hosted add-ins.

在 SharePoint 托管的加载项中使用客户端人员选取器控件Use the client-side People Picker control in a SharePoint-hosted add-in

在页面标记中In your page markup

  1. 添加对客户端人员选取器控件的脚本依赖关系的引用。Add references to the client-side People Picker control's script dependencies.

  2. 添加页面 UI 的 HTML 标记。此示例中的外接程序定义两个 div 元素:一个用于要呈现在其中的选取器,一个用于 UI:一个调用脚本以查询选取器和显示用户信息的元素的按钮。Add the HTML tags for the page UI. The add-in in this example defines two div elements: one for the picker to render in and one for the UI: a button that invokes script to query the picker and the elements that display user information.

在脚本中In your script

  1. 创建 JSON 字典来用作存储特定于选取器的属性的架构,例如 AllowMultipleValuesMaximumEntitySuggestionsCreate a JSON dictionary to use as a schema that stores picker-specific properties, such as AllowMultipleValues and MaximumEntitySuggestions.

  2. 调用 SPClientPeoplePicker_InitStandaloneControlWrapper 全局函数。Call the SPClientPeoplePicker_InitStandaloneControlWrapper global function.

  3. 从页面中获取选取器对象。Get the picker object from the page.

  4. 查询选取器。Query the picker. 此示例中的加载项调用 GetAllUserInfo 方法来获取已解析的用户的所有用户信息,并调用 GetAllUserKeys 方法来仅获取已解析的用户的密钥。The add-in in this example calls the GetAllUserInfo method to get all user information for the resolved users, and the GetAllUserKeys method to just get the keys for the resolved users.

  5. 使用 JavaScript 对象模型获取用户 ID。用户 ID 不包含在选取器返回的信息中,所以该外接程序调用 SP.Web.ensureUser 方法并从返回的 SP.User 对象中获取 ID。Get the user ID by using the JavaScript object model. The user ID isn't included in the information that's returned by the picker, so the add-in calls the SP.Web.ensureUser method and gets the ID from the returned SP.User object.

选取器的呈现、初始化及其他功能由服务器处理,包括针对 SharePoint 身份验证提供程序搜索并解析用户输入。Rendering, initializing, and other functionality for the picker are handled by the server, including searching and resolving user input against the SharePoint authentication providers.

代码示例:在 SharePoint 托管的加载项中使用客户端人员选取器Code example: Using the client-side People Picker in a SharePoint-hosted add-in

以下 HTML 和 JavaScript 代码示例将客户端人员选取器控件添加到 SharePoint 托管的加载项。The following HTML and JavaScript code examples add a client-side People Picker control to a SharePoint-hosted add-in.

第一个示例演示 Default.aspx 页面中 PlaceHolderMain asp:Content 标记的页面标记。The first example shows the page markup for the PlaceHolderMain asp:Content tags in the Default.aspx page. 此代码引用选取器的脚本依赖项,为 DOM 元素(选取器会在其中呈现)提供唯一 ID,并定义加载项的 UI。This code references the picker's script dependencies, gives a unique ID to the DOM element where the picker renders, and defines the add-in's UI.

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

备注

根据你的环境,可能不必明确引用所有这些依赖关系。Depending on your environment, you might not have to explicitly reference all of these dependencies.


下面的示例显示来自 App.js 文件的脚本The following example shows the script from the App.js file. 此脚本初始化并呈现选取器,查询它以获取用户信息,然后使用 JavaScript 对象模型获取该用户 ID。This script initializes and renders the picker, queries it for user information, and then gets the user ID by using the JavaScript object model.


// 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());
}

另请参阅See also