Extracting information from "Created By" field - sharepoint

Is there any way I could extract the department or email information from the "Created By" field in a custom list?

You should be more specific how you want to extract the information, if it's javascript or c# or via UI.
Here is a simple example, maybe you can do something with it. Let me know if you have any questions.
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle('Kalender');
//this query can be done in other ways, I'm getting all items
var query = SP.CamlQuery.createAllItemsQuery();
var items = list.getItems(query);
ctx.load(items);
ctx.executeQueryAsync(function () {
var itemsEnum = items.getEnumerator();
while (itemsEnum.moveNext()) {
var item = itemsEnum.get_current();
var author = item.get_item('Author');
console.log("Email: " + author.get_email());
console.log("Name: " + author.get_lookupValue());
console.log("ID: " + author.get_lookupId());
}
}, function(sender, args) {
console.log(args.get_message());
});

Related

Not able to query SharePoint from Nintex form custom JavaScript

I'm trying to query the SharePoint list using JSOM from Nintex custom javascript. My intention is to show the data in Nintex multiLine textbox. I can query data from SharePoint and display it in the Nintex edit form and not able to query from the Nintex view/display form.
Any thoughts? Thanks!.
Please refer the below code
var clientContext;
var oListItem;
var workFlowListName = "sharepoint Tasks";
var requestId = 1;
var pollSP;
function checkSPLoad() {
if (clientContext) {
window.clearInterval(pollSP);
if (requestId)
GetPFItems();
}
}
function GetPFItems() {
var oList = clientContext.get_web().get_lists().getByTitle(workFlowListName);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Text'>" + requestId
+ "</Value></Eq></Where></Query></View>");
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.PFQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));
}
function PFQuerySucceeded(sender, args) {
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
pfTaskName = oListItem.get_item('TaskName');
NWF$('#'+'sampleTextBox').val(pfTaskName);
}
}
function onQueryFailed(sender, args) { }
Why your CAML Query has data type as Text for ID field? Also, You need to configure multiline textbox's setting and make display mode as Edit. This should start getting populated.

restricting the numbers of items to be added tosharepoint list per day

is there anyway that we could restrict the number of items to be added to a list for instance 30 items can be only added in 1 day. and then a message should appear if the number 31 tried to add new item, and tomorrow users will also be able to add 30 items and so on.
I found the below script that could limit the over all number of items to be added to 60.
<input type="button" value="Sign Up Now!" onclick="createItemIfBelowLimit()" />
<script>
function createItemIfBelowLimit(){
var max = 60;
var listTitle = "Your List Title";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listTitle);
clientContext.load(list);
clientContext.executeQueryAsync(function(){
var itemCount = list.get_itemCount();
if(itemCount < max){
createItem(listTitle,{
"Title":"Example title text",
"Body":"Example body text"
});
}else{
alert("This sign-up list is full. Sorry!");
}
},function(sender,args){
alert(args.get_message());
});
}
function createItem(listTitle,values){
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listTitle);
var newItem = list.addItem();
for(var key in values){
newItem.set_item(key,values[key]);
}
newItem.update();
clientContext.load(newItem);
var rootFolder = list.get_rootFolder(); // Note: use a list's root folder to determine its server relative URL
clientContext.load(rootFolder);
clientContext.executeQueryAsync(function(){
var itemId = newItem.get_item("ID");
SP.UI.ModalDialog.showModalDialog(
{
title: "Item #"+itemId+" Created Successfully!",
url: rootFolder.get_serverRelativeUrl() + "/DispForm.aspx?ID="+itemId
}
);
},function(sender,args){
alert(args.get_message());
});
}
</script>
If you can use SharePoint server object model then solid solution would be to implement SharePoint list item event receiver class based on SPItemEventReceiver class where you can override method
public override void ItemAdding(SPItemEventProperties properties)
and then cancel adding new list item to list by using code:
properties.Status = SPEventReceiverStatus.CancelNoError;
Modify the code as below to achieve it, add the CAML Query to get all today added items, and check the item count.
<script type="text/javascript" language="javascript">
ExecuteOrDelayUntilScriptLoaded(createItemIfBelowLimit, "sp.js");
function createItemIfBelowLimit(){
var max = 30;
var listTitle = "Your List Title";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listTitle);
var camlQuery = new SP.CamlQuery();
var query="<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'><Today/></Value></Eq></Where></Query></View>";
camlQuery.set_viewXml(query);
this.collListItem = list.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(function(){
var itemCount = collListItem.get_count();
if(itemCount < max){
createItem(listTitle,{
"Title":"Example title text",
"Body":"Example body text"
});
}else{
alert("This sign-up list is full. Sorry!");
}
},function(sender,args){
alert(args.get_message());
});
}
function createItem(listTitle,values){
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listTitle);
var newItem = list.addItem();
for(var key in values){
newItem.set_item(key,values[key]);
}
newItem.update();
clientContext.load(newItem);
var rootFolder = list.get_rootFolder(); // Note: use a list's root folder to determine its server relative URL
clientContext.load(rootFolder);
clientContext.executeQueryAsync(function(){
var itemId = newItem.get_item("ID");
SP.UI.ModalDialog.showModalDialog(
{
title: "Item #"+itemId+" Created Successfully!",
url: rootFolder.get_serverRelativeUrl() + "/DispForm.aspx?ID="+itemId
}
);
},function(sender,args){
alert(args.get_message());
});
}
</script>

Sharepoint: How to easily get related child items using JSOM

Suppose I have 2 Lists: Teams and Employees. Each team has a number of employees:
Teams
ID
Name
Employees
ID
Name
TeamID (foreign key of Teams)
Is it possible to write a query in SharePoint JSOM such that I could do something along the following lines (after the query executes/loads):
var employeesListItems = teamListItem.get_item("Employees")
Does SharePoint Object Model support this in any way?
Clarification: my intent is to reuse the ClientObject as much as I can. I understand that I could query for all employees and all teams, create an array of custom objects for each, and then iterate over employees and push them to onto the "Employees" field of the related Team object. I would like to avoid doing so.
Even though SharePoint CAML supports List Joins and Projections, in that case I would suggest you a different approach.
The following example demonstrates how to retrieve parent/child items using a single request:
function getItemWithDetails(parentListTitle,childListTitle,lookupFieldName,lookupFieldValue,success,error)
{
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var lists = web.get_lists();
var parentList = lists.getByTitle(parentListTitle);
var parentItem = parentList.getItemById(lookupFieldValue);
var childList = lists.getByTitle(childListTitle);
var childItems = childList.getItems(createLookupQuery(lookupFieldName,lookupFieldValue));
ctx.load(parentItem);
ctx.load(childItems);
ctx.executeQueryAsync(
function() {
success(parentItem,childItems);
},
error
);
}
function createLookupQuery(lookFieldName,lookupFieldValue)
{
var queryText =
"<View>" +
"<Query>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name='{0}' LookupId='TRUE'/>" +
"<Value Type='Lookup'>{1}</Value>" +
"</Eq>" +
"</Where>" +
"</Query>" +
"</View>";
var qry = new SP.CamlQuery();
qry.set_viewXml(String.format(queryText,lookFieldName,lookupFieldValue));
return qry;
}
Usage
var parentListTitle = 'Teams';
var childListTitle = 'Employees'
var lookupFieldValue = 1;
var lookupFieldName = 'Team';
getItemWithDetails(parentListTitle,childListTitle,lookupFieldName,lookupFieldValue,
function(teamItem,employeeItems){
//print parent item
console.log(teamItem.get_item('Title'));
//print child items
for(var i = 0; i < employeeItems.get_count(); i++){
var employeeItem = employeeItems.getItemAtIndex(i);
console.log(employeeItem.get_item('Title'));
}
},
function(sender,args){
console.log(args.get_message());
});
Another option is to utilize List Joins and Projections. The following example demonstrates how to retrieve employee list items with projected team items
function getListItems(listTitle,joinListTitle,joinFieldName,projectedFields,success,error)
{
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var items = list.getItems(createJoinQuery(joinListTitle,joinFieldName,projectedFields));
ctx.load(items);
ctx.executeQueryAsync(
function() {
success(items);
},
error
);
}
function createJoinQuery(joinListTitle,joinFieldName,projectedFields)
{
var queryText =
"<View>" +
"<Query/>" +
"<ProjectedFields>";
for(var idx in projectedFields) {
queryText += String.format("<Field Name='{0}_{1}' Type='Lookup' List='{0}' ShowField='{1}' />",joinListTitle,projectedFields[idx]);
}
queryText +=
"</ProjectedFields>" +
"<Joins>" +
"<Join Type='INNER' ListAlias='{0}'>" +
"<Eq>" +
"<FieldRef Name='{1}' RefType='Id'/>" +
"<FieldRef List='{0}' Name='ID'/>" +
"</Eq>" +
"</Join>" +
"</Joins>" +
"</View>";
var qry = new SP.CamlQuery();
qry.set_viewXml(String.format(queryText,joinListTitle,joinFieldName));
return qry;
}
Usage
var listTitle = 'Employees';
var joinListTitle = 'Teams'
var joinFieldName = 'Team';
var projectedFields = ['ID','Title'];
getListItems(listTitle,joinListTitle,joinFieldName,projectedFields,
function(employeeItems){
//print items
for(var i = 0; i < employeeItems.get_count(); i++){
var employeeItem = employeeItems.getItemAtIndex(i);
var employeeName = employeeItem.get_item('Title');
var teamName = employeeItem.get_item('Teams_Title').get_lookupValue();
console.log(employeeName + ',' + teamName);
}
},
function(sender,args){
console.log(args.get_message());
});
Probably you can not achieve what you want, because of lookup configuration. But you could do the following:
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var lists = web.get_lists();
var teams = lists.getByTitle("Teams");
var employees = lists.getByTitle("Employees");
//just get the first item
var employee = employees.getItemById(1);
ctx.load(employee)
ctx.executeQueryAsync(function() {
var team = employee.get_item("TeamID");
// both the id and the value of the lookup field
var lookupId = team.get_lookupId();
var lookupValue = team.get_lookupValue();
// let's grab all the fields
var fullTeam = teams.getItemById(lookupId)
ctx.load(fullTeam)
ctx.executeQueryAsync({
var name = fullTeam.get_item("Name");
alert("We can get the Name field of the lookup field: " + name);
});
});
I guess, it a bit reverse of what you really intent to achieve but still this way you will exploit CSOM.

Need Help: Account Name on Contact Phone Call

I am new to CRM and have been able to figure out everything up to now. I have read so many post and internet post and tried them. I have watched some many videos. It seems it should be easy. The contact record has the ParentCustomerID, and ParentCustomerName that holds the account if there is one associated. Now I am just totally confused on the required steps.
Requirement: - I need Account Name to be displayed on the contact level phone call form and saved in phone call table so that it can be visible in the phone call view.
I have in Phone Call N:1 Relationship field str_companyid (lookup) primary Entity is Account with Referential behavior.
I tried a Phone Call N:1 Relationship field new_companystring (lookup) primary Entity is Contact with Referential behavior. I came to the conclusion that this is not a valid approach. Let me know if incorrect.
Do I need a N:N instead?
I have added the str_companyid field to the form. I went to the "Create a phone call for a contact" workflow process. On the "Create PhoneCall" step I have added the dynamic field {Company(Contact)}. After save and publishes; I created a phone call and it isn't populated.
I have tried different Web Resource JS. I have added the JS in the onload of the form properties.
Why doesn't something as easy as this work? I can't seem to get the retrieveRecord to work. I have also tried the xmlHttpObject object but it returns 0.
Can someone help assist me on what I am missing? What are the complete steps to accomplish this?
![I have screenshots below and the code I was running][1]
function PopulateCompanyName()
{
//get group GUID
if (Xrm.Page.getAttribute("to").getValue()[0].id != null) {
var lookup = Xrm.Page.getAttribute("to").getValue();
alert(lookup[0].id);
alert(lookup[0].typename);
alert(lookup[0].name);
alert(lookup);
SDK.JQuery.retrieveRecord(lookup[0].id,
lookup[0].typename,
"ParentCustomerID",
null,
function (lookup) {
Xrm.Page.getAttribute("Company").setValue(lookup[0].str_companyid);
});
}
else {
Xrm.Page.getAttribute("str_companyid").setValue(null);
}
}
function GetCompany()
///Get lookup ID
{
alert("I am Here");
var lookupfield = Xrm.Page.getAttribute("to").getValue();
if (lookupfield != null && lookupfield [0] != null)
{
var householdlookupvalue = lookupfield [0].id;
}
else
{
var householdlookupvalue = " ";
}
alert("I am here2");
alert(householdlookupvalue);
}
// Prepare variables for a contact to retrieve.
var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();
// Prepare the SOAP message.
var xml = ""+
""+
authenticationHeader+
""+
""+
"contact"+
""+lookupfield [0].id+""+
""+
""+
"parentcustomerid"+
""+
""+
""+
""+
"";
alert(xml );
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result.
var resultXml = xHReq.responseXML;
alert("at results");
var errorCount = resultXml.selectNodes('//error').length;
alert("errorCount " + errorCount); ////////////////////////////////////returns 0; it shouldn't
alert("After the result XML "+resultXml .toString() + " ::::");
// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
}
// Display the retrieved value.
else
{
//Create an array to set as the DataValue for the lookup control.
var lookupData = new Array();
//Create an Object add to the array.
var lookupItem= new Object();
//Set the id, typename, and name properties to the object.
lookupItem.id = resultXml.selectSingleNode("//q1:parentcustomerid").nodeTypedValue;
lookupItem.entityType = 'account';
lookupItem.name = resultXml.selectSingleNode("//q1:parentcustomerid").getAttribute("name");
// Add the object to the array.
lookupData[0] = lookupItem;
alert(lookupitem.name)
// Set the value of the lookup field to the value of the array.
Xrm.Page.getAttribute("str_companyid").setValue(lookupData);
}
var contact = new Array();
contact = Xrm.Page.getAttribute("to").getValue();
alert("I am here");
alert(contact);
if (contact == null || contact[0].entityType != "contact" || contact.length > 1) {
return;
}
alert("inside if")
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=ParentCustomerId&$filter=ContactId eq guid'" + contact[0].id + "'";
var retrieveReq = new XMLHttpRequest();
retrieveReq.open("GET", oDataSelect, false);
retrieveReq.setRequestHeader("Accept", "application/json");
retrieveReq.setRequestHeader("Content-Type", "application/json;charset=utf-8");
retrieveReq.onreadystatechange = function () {
GetContactData(this);
};
retrieveReq.send();
}
I replied in the other forum but I post here as reference and with more technical details.
The to attribute of phonecall entity is a partylist type, this means that it can handle several records from different entities. In your case you want to get the Parent Account (field parentcustomerid) if a contact is inside the to field.
Your first code contains same typo and use the msdn Retrieve example, the second code uses CRM 4.0 endpoints, they are still supported inside CRM 2011, but it's better to avoid them so you can use the REST endpoint instead of the SOAP one.
a working code in your case can be:
function setToParentAccount() {
// set only if to Field (Recipient) has 1 record and is a contact
if (Xrm.Page.getAttribute("to").getValue() != null) {
var recipient = Xrm.Page.getAttribute("to").getValue();
if (recipient.length == 1 && recipient[0].entityType == "contact") {
var contactId = recipient[0].id;
var serverUrl;
if (Xrm.Page.context.getClientUrl !== undefined) {
serverUrl = Xrm.Page.context.getClientUrl();
} else {
serverUrl = Xrm.Page.context.getServerUrl();
}
var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var contactRequest = new XMLHttpRequest();
contactRequest.open("GET", ODataPath + "/ContactSet(guid'" + contactId + "')", false);
contactRequest.setRequestHeader("Accept", "application/json");
contactRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
contactRequest.send();
if (contactRequest.status === 200) {
var retrievedContact = JSON.parse(contactRequest.responseText).d;
var parentAccount = retrievedContact.ParentCustomerId;
if (parentAccount.Id != null && parentAccount.LogicalName == "account") {
var newParentAccount = new Array();
newParentAccount[0] = new Object();
newParentAccount[0].id = parentAccount.Id;
newParentAccount[0].name = parentAccount.Name;
newParentAccount[0].entityType = parentAccount.LogicalName;
Xrm.Page.getAttribute("str_companyid").setValue(newParentAccount);
} else {
Xrm.Page.getAttribute("str_companyid").setValue(null);
}
} else {
alert("error");
}
} else {
Xrm.Page.getAttribute("str_companyid").setValue(null);
}
}
}
to be called inside OnLoad event and OnChange event of the to field.

Add group to list using SharePoint 2010 JSOM

Can someone give me an example of adding a SharePoint group to a list using the javascript client object model. I was able to create groups and add them to the site but I haven't seen any documentation on adding the groups to a list? I know how to do this via c# but not javascript.
How to grant permissions for Group in List via CSOM (JavaScript) in SharePoint 2013
The following example demonstrates how to grant Contribute permissions for group Approvers in list:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var group = web.get_siteGroups().getByName("Approvers");
var roleDef = web.get_roleDefinitions().getByType(SP.RoleType.contributor);
var roleDefBindings = SP.RoleDefinitionBindingCollection.newObject(context);
roleDefBindings.add(roleDef);
list.get_roleAssignments().add(group,roleDefBindings);
list.update();
context.load(group);
context.load(list);
context.load(roleDef);
context.executeQueryAsync(
function () {
console.log('For group ' + group.get_title() + ' has been granted ' + roleDef.get_name() + ' permissons in List ' + list.get_title());
},
function (sender, args) {
console.log("Error: " + args.get_message());
}
);
Since SP.GroupCollection does not contain the method getByName in SharePoint 2010, use the method SP.GroupCollection.getById(id) instead to return Group client object:
var group = web.get_siteGroups().getById(16); //get Approvers group by Id
function getGroupByName(groupName, completeFunction) {
if (groupName == null) {
throw new Error("Group Name cannot be null");
}
var rv = null;
var currentContext = SP.ClientContext.get_current();
var currentWeb = currentWeb = currentContext.get_web();
var allGroups = currentWeb.get_siteGroups();
currentContext.load(allGroups);
currentContext.executeQueryAsync(getGroupByName_Success, getGroupByName_Failed);
function getGroupByName_Success() {
var groupEnumerator = allGroups.getEnumerator();
while (groupEnumerator.moveNext()) {
rv = groupEnumerator.get_current();
var groupTitle = rv.get_title();
if (groupTitle == groupName) {
groupFound = true;
break;
}
}
if (groupFound == false) {
rv = null;
}
completeFunction(rv);
}
function getGroupByName_Failed(sender, args) {
alert("Error Occurred: " + args.get_message() + "\n" + args.get_stackTrace());
}
}

Resources