New to SharePoint Online:
Goal: - Have the user enter a name in the input box (senderName), using the PeoplePicker, username populates... Once the username is selected, email of user populates in the email column in SharePoint and username gets stored in SharePoint column also.
2 Columns in SharePoint: 1. senderName 2. fromEmail
Languages using:
- HTML
- Javascript
The HTML
<div class="form-group row">
<div class="col-md-6">
<div id="divResult"></div>
<div class="col-md-6">
<label for="senderName">Name</label>
<div id="peoplePickerDiv"></div>
</div>
</div>
<button type="button" class="btn btn-primary btn-block" id="submit">Submit</button>
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/central-support-services"; // root name
var listName = "PackDelivery"; // 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 + "/_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.PackDeliveryListItem";//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
//"from":$("#from").val(),
"formDate":$("#formDate").val(),
"senderName":$("#peoplePickerDiv .ms-entity-resolved").text(),
"departmentChoice":$("#departmentChoice").val(),
"shippedTo":$("#shippedTo").val(),
"inputAddress":$("#inputAddress").val(),
"inputCity":$("#inputCity").val(),
"inputState":$("#inputState").val(),
"inputZip":$("#inputZip").val(),
"shippedFrom":$("#shippedFrom").val(),
"carrier":$("#carrier").val(),
"carrierOther":$("#otherCarrier").val(),
"method":$("#method").val(),
"methodOther":$("#otherMethod").val(),
"details": multilineString,
"dateReceived":$("#dateReceived").val(),
"fromEmail":$("#fromEmail").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";
}
I've used in my HTML to get the username to stick and save onto a the SharePoint list but can't get how to get the email.
HTML script used:
$(function () {
initializePeoplePicker('peoplePickerDiv');
bindButtonClick();
});
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);
}
function bindButtonClick() {
$("#submit").on("click", function () {
addListItem();
});
}
function addListItem() {
var title = $("#txtTitle").val();
var senderName = $("#peoplePickerDiv .ms-entity-resolved").text();
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('PackDelivery');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
//oListItem.set_item('Title', title);
oListItem.set_item('senderName', senderName);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onAddSucceeded),
Function.createDelegate(this, this.onAddFailed)
);
}
function onAddSucceeded(sender, args) {
$("#divResult").html("Item successfully added!");
}
function onAddFailed(sender, args) {
alert('Request failed. ' + args.get_message() +'\n' + args.get_stackTrace());
}
I made sure to bring in the following scripts as well:
<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
<script type="text/javascript" src="_layouts/15/strings.js"></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.core.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>