获取People Picker div中的用户名,以便SharePoint Online 365使用JavaScript在列中发布

时间:2018-03-16 19:57:24

标签: javascript jquery html sharepoint

注意:SharePoint新手

我能够让peoplepicker div工作,但我需要帮助获取名称值或显示名称以在名为Person的SharePoint列中发布。目前,一旦用户提交Person列就会出现空白。抱歉缺乏知识,只是有点迷失。

$(document).ready(function() {
   initializePeoplePicker('peoplePickerDiv');
    });

   function initializePeoplePicker(peoplePickerElementId) {
      // Create a schema to store picker properties, and set the properties.
      var schema = {};
      schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
      //This value specifies where you would want to search for the valid values
      schema['SearchPrincipalSource'] = 15;
      //This value specifies where you would want to resolve for the valid values
      schema['ResolvePrincipalSource'] = 15;
      schema['AllowMultipleValues'] = true;
      schema['MaximumEntitySuggestions'] = 50;
      // schema['Width'] = '780px';
      // 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);
    }

   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());
  }
<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="format-detection" content="telephone=no" />
		<title>Package Delivery</title>
		<link rel="stylesheet" href="../SiteAssets/Package%20Delivery/bootstrap/css/bootstrap.min.css">
		<link rel="stylesheet" href="../SiteAssets/Package%20Delivery/css/style.css">
		<!--[if IE]>
	    <script src="http://html5shi../SiteAssets/javier/v.googlecode.com/svn/trunk/html5.js"></script>
	    <![endif]-->
	</head>
	<body>
		<div class="container">
			<div id="contact" method="post">
				<div class="row">
					<div class="col-md-12">
						Recipient's Name
						<div id="peoplePickerDiv"></div>
						<!-- <input class="form-control input-sm" name="Sender" id="sender" placeholder="Enter Person to Notify">-->
					</div>

我正在使用javascript文件获取它们的值:

/*=========================================
 * SharePoint Repeating Field Form Template
=========================================*/

/*TODO:

Connect Profile Properties
Test Submission
Make everything generic
Post to GitHub
*/

var baseURI = "https://berkeleycollege365.sharepoint.com/sites/"; // root name
var siteName = "central-support-services";
var listName = "PackageDelivery"; // list name

$( document ).ready(function() {
   // getUserProperties();
});

function getUserProperties(){
  var requestUriCom = "https://berkeleycollege365.sharepoint.com/_api/SP.UserProfiles.PeopleManager/getmyproperties";
  $.ajax({
    url: requestUriCom,
    headers:{"Accept":"application/json; odata=verbose"},
			contentType:'application/json; odata=verbose',
      Type: 'GET',
      success: onSuccessUser,
    error: function (data) {console.log(data);}
  })
}

function onSuccessUser(data){
  //console.log(data);
  //Parse the return allll the way down.
  var parse = data.d.UserProfileProperties.results[4].Value;
}

$('[data-ssd-dynamic-wrapper]').ssdDynamicRows({
  clear_warning: function(row) {
    row.find('[data-validation] [data-case]').removeClass('show');
    row.find(':input').removeClass('warning');
  },
    other_elements: {
		  '[data-validation]' : 'data-validation'
		}
});

$('#submit').on('click', function(event) {
  console.log("working");
  event.preventDefault();

  $(this).find('[data-case="required"]').removeClass('show');
  $('#result').empty();

  var inputs = $(this).find(':input').removeClass('warning');
    inputs.each(function() {
      if ($(this).val() === '') {
        $(this).addClass('warning')
          .closest('[data-ssd-dynamic-field]')
          .find('[data-case="required"]')
          .addClass('show');
      }
    });
        /************************
        You probably dont have to edit this.
        This will account for any new fields in the repeating section and add the correct key value pairs.
        Again, probably dont have to edit this.
        Placed all of the stuff you SHOULD edit under the next comment break.
        *************************/
    var a = [];
    var fullString = "";
    //We iterate through each row...
    $('.itemRow').each(function(i){
			//setting up our second array
      var b = [];
      //We are in our rows, so now we will find and iterate through the inputs within that row
	    $(this).find(':input').each(function(i, key){
        //getting the value
        var c = this.value;
        //getting the name and splitting off the unique identifier so we can use it as our key name
        var d = $(this).attr('name');
          d = d.substr(0,d.indexOf('-'));
          //pushing the information into our secondary array
          b.push([d,c]);
      });
        var i = 0;
        var key;
				var val;
        var obj = {};
        //Here, we will take the values from our secondary array and form our objects
        //We also create our string here
          for (i;i < b.length;i++){
            key = b[i][0];
            obj[key] = b[i][1];
            val = b[i][1];
            fullString += key + ":" + val + " ";
          }
          //Push the objects into our main array
          a.push(obj);
          //Toss on a line break for our rich text fields
          fullString+="<br>";
    });
        //Extend our array
        var convertedA = $.extend({},a);
        //Turn everything into a JSON object so we can store and retrieve it
        //var convertedB = JSON.stringify(convertedA);
        /*******************************
        ********************************
        Here you can choose what to pass for submission.
        ********************************
        *******************************/
        createItem(fullString);
        location.reload() // Reloads screen after hitting submit button
});

function createItem(multilineString) {
    console.log("First String"+multilineString);
    //Setting up the URL to the list we will post to.
    var itemUrl = baseURI + siteName + "/_api/web/lists/getByTitle('"+ listName +"')/items";
    //This applies the correct content type for this list item.  You can find the function for this towards the end of the script.
    var itemType = "SP.Data.PackageDeliveryListItem";//getListItemType(listName);
    //Hardcoding the metadata we are passing as this can only serve one function.
    var item = {
       "__metadata": { "type": itemType },
       "Title":"Title", //Setup your data here
       "date":$("#date").val(),
			 "from":$("#from").val(),
       "departmentChoice":$("#departmentChoice").val(),
       "shippedTo":$("#shippedTo").val(),
       "shippedFrom":$("#shippedFrom").val(),
       "carrier":$("#carrier").val(),
       "method":$("#method").val(),
       "Date_x0020_Received":$("#ReceivedDate").val(),
       "Person": $("#peoplePickerDiv").val(),
       //"Person": $.get("getUserInfo()"),
       "Details": multilineString,
       "Form_x0020_Filled_x0020_By":$("#filledBy").val(),
       "Date_x0020_Filled":$("#dateFilled").val(),
       "Email_x0020_Sent_x0020_On":$("#emailSent").val(),
			 "deliveryOther":$("#deliveryOther").val()
	  };
     //Turn everything into a JSON object
     var body = JSON.stringify(item);
	     //Post the item
       $.ajax({
		       url: itemUrl,
		       type: "POST",
		       contentType: "application/json;odata=verbose",
		       data: body,
		       headers: {
	           "Accept": "application/json;odata=verbose",
	           "X-RequestDigest": $("#__REQUESTDIGEST").val()
		       },
		       success: function(data){console.log(data);},
		       error: function (data) {console.log(data);}
         });
}
 // Getting the item type for the list
function getListItemType(name) {
   return"SP.Data." + name[0].toUpperCase() + name.substring(1) + "ListItem";
}

1 个答案:

答案 0 :(得分:0)

要使用REST API设置用户或组字段列,请检查用户字段值的格式,如下所示:

<强> single-valued user field: '<user field name>' : <user id>

<强> multi-valued user field: '<user field name>' : { 'results': [<array of user ids>]}

示例:

单用户字段值

var item = {
   "__metadata": { "type": itemType },
   "Title":"Title", //Setup your data here  
   "PersonId": 10
};

多个用户字段值

var item = {
   "__metadata": { "type": itemType },
   "Title":"Title", //Setup your data here  
   "PersonId": {"results": [10,11,12] }  //multi-valued User field value 
};

因此,在使用REST API将列表项添加到列表之前,请从People Picker获取用户ID。