How do I get ID from an SPListItemCollection in javascript? - javascript

I have a Sharepoint 2010 list. Each item can have an "related item" in a second list ('extended').
I use the following code to determine if that related item exists or not (using list.getItems).
If it does exist I would like to read the ID of that item (from the "listCollection") and use that to open up the display form for that item. But how do I get the ID of the item from the object in my listCollection?
var listCollection;
function getExtended() {
try {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('Extended');
var query = '<View Scope=\'RecursiveAll\'>'+
'<Query>'+
'<Where>'+
'<Contains>'+
'<FieldRef Name=\'MainId\'/>' +
'<Value Type=\'Integer\'>' + GetId() +'</Value>'+
'</Contains>'+
'</Where>'+
'</Query>'+
'</View>';
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(query);
this.listCollection= list.getItems(camlQuery);
context.load(this.listCollection, 'Include(MainId, Status, ID)');
context.executeQueryAsync(Function.createDelegate(this, this.listReceived), Function.createDelegate(this, this.failed));
}
catch (e) {
alert(e);
}
}
function listReceived() {
var count=this.listCollection.get_count();
if (count==0){
$("#extendButton").html("<input type='button' onclick='NewExt()' value='Create new extended'/>");
} else {
$("#extendButton").html("<button>Show extended</button>");
}
}

It's interesting to re-read my question and not be entirely clear what I was asking myself. But the code I used in the end was simply:
var listItemEnumerator = this.listCollection.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
childId= oListItem.get_item('ID');
}
Which at least worked, even if I'm handling the (one-item) list in an overly-complex way.

Related

Sharepoint: Lookup against a large list with CAML Query

I have a SharePoint List (list_dls) which has all the Email addresses. The list has a single column with Field name "Title". I need to validate that the Item in the "LookupField" is contained in the 'list_dls'. The list has over 5000 emails, hence I will need to do a CAML query. The script does not seem to find the item. Any ideas to get it to work would be really appreciated.
Here is the code.
<input type='button' value='get Lists' onclick="PopulateLookupField();"/>
<p id="demo"></p>
<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var LookupField = 'lnam#xyz.com';
function PopulateLookupField()
{
var clientContext = new SP.ClientContext.get_current();
var LookupList = clientContext.get_web().get_lists().getByTitle('list_dls');
var camlQuery_list = new SP.CamlQuery();
camlQuery_list.ViewXml = #"<View Scope='RecursiveAll'><ViewFields><FieldRef Name='ID'/><FieldRef Name='Title'/></ViewFields><RowLimit Paged='TRUE'>5000</RowLimit></View>";
LookupList<ListItem> allListItems = new LookupList<ListItem>();
do
{
var listItemCollection = LookupList.GetItems(camlQuery_list);
clientContext.Load(listItemCollection);
clientContext.ExecuteQuery();
allListItems.AddRange(listItemCollection);
var ItemFound = listItemCollection.Where(item => item.FieldValues["Title"].ToString().Contains(LookupField);
if(ItemFound !== null){break;}
camlQuery_list.ListItemCollectionPosition = listItemCollection.ListItemCollectionPosition;
} while (camlQuery_list.ListItemCollectionPosition != null);
clientContext.load(ItemFound);
alert("ItemFound = " + ItemFound);
}
</script>
First, go to the SharePoint list "list_dls" and create a new index for Title column (maybe is already done)
https://support.microsoft.com/en-us/office/add-an-index-to-a-list-or-library-column-f3f00554-b7dc-44d1-a2ed-d477eac463b0
Also, you can search immediately with caml query in a list
camlQuery_list.ViewXml = $"<View><Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{LookupField}</Value></Eq></Where></Query></View>";
ListItemCollection collection = LookupList.GetItems(camlQuery_list);
context.Load(collection);
context.ExecuteQuery();
if (collection.Count > 0)
{
var yourItem = collection[0];
}

SharePoint JavaScript Display Value from Lookup Field

Existing system has HTML, JavaScript forms with the following:
SharePoint List, "CustomerType" with values
SharePoint List, "Customer" with lookup column named, "CustomerType" pulling values from "CustomerType"
Need to add a new field so I mirrored the "CustomerType" by creating:
SharePoint List, "CustomerSegmentation" with values
SharePoint List, "Customer" with lookup column named, "CustomerSegmentation" pulling values from "CustomerSegmentation"
I copied the HTML, JavaScript, etc. - It is all working well for selecting a value and creating the item in the "customer" list. However, when I try to display the selected value on a 'display' HTML form using:
var CustomerSegmentationField = oListItem.get_item('CustomerSegmentationField');
if (checkNotEmpty(CustomerSegmentationField)) {
$("#selCustomerSegmentationField").val(CustomerSegmentationField.get_lookupId());
}
I get this error:
Uncaught Error: The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
at Function.Error.create (ScriptResource.axd?d=k5RfMmPNK2hWIceXJ8-ajx3E8J_9Fwh_cmdsa2b8w5b_6SdxoV5CP7PTQYU2geZFptqlColfo4USOXQsdBih3W0VS_49yn_5vEAL69UdI91yC-tDiYJ5qy_HJzfGk6ituovIGh_kYQ43NWRInP8bleYrT4aM9uWrD_zUrKaOdVSegfYI0_gHDDpmP74zGEwh0&t=ffffffffecf19baa&ctag=200622:formatted:177)
at SP.ListItem.$1D_2 (sp.js:formatted:15164)
at SP.ListItem.get_item (sp.js:formatted:14868)
at onQuerySucceeded (Display-New-Request.aspx?itemID=9076:1678)
at Array. (ScriptResource.axd?d=k5RfMmPNK2hWIceXJ8-ajx3E8J_9Fwh_cmdsa2b8w5b_6SdxoV5CP7PTQYU2geZFptqlColfo4USOXQsdBih3W0VS_49yn_5vEAL69UdI91yC-tDiYJ5qy_HJzfGk6ituovIGh_kYQ43NWRInP8bleYrT4aM9uWrD_zUrKaOdVSegfYI0_gHDDpmP74zGEwh0&t=ffffffffecf19baa&ctag=200622:formatted:23)
at ScriptResource.axd?d=k5RfMmPNK2hWIceXJ8-ajx3E8J_9Fwh_cmdsa2b8w5b_6SdxoV5CP7PTQYU2geZFptqlColfo4USOXQsdBih3W0VS_49yn_5vEAL69UdI91yC-tDiYJ5qy_HJzfGk6ituovIGh_kYQ43NWRInP8bleYrT4aM9uWrD_zUrKaOdVSegfYI0_gHDDpmP74zGEwh0&t=ffffffffecf19baa&ctag=200622:formatted:2555
at SP.ClientRequest.$3K_0 (sp.runtime.js:2)
at Array. (ScriptResource.axd?d=k5RfMmPNK2hWIceXJ8-ajx3E8J_9Fwh_cmdsa2b8w5b_6SdxoV5CP7PTQYU2geZFptqlColfo4USOXQsdBih3W0VS_49yn_5vEAL69UdI91yC-tDiYJ5qy_HJzfGk6ituovIGh_kYQ43NWRInP8bleYrT4aM9uWrD_zUrKaOdVSegfYI0_gHDDpmP74zGEwh0&t=ffffffffecf19baa&ctag=200622:formatted:23)
at ScriptResource.axd?d=k5RfMmPNK2hWIceXJ8-ajx3E8J_9Fwh_cmdsa2b8w5b_6SdxoV5CP7PTQYU2geZFptqlColfo4USOXQsdBih3W0VS_49yn_5vEAL69UdI91yC-tDiYJ5qy_HJzfGk6ituovIGh_kYQ43NWRInP8bleYrT4aM9uWrD_zUrKaOdVSegfYI0_gHDDpmP74zGEwh0&t=ffffffffecf19baa&ctag=200622:formatted:2555
at Sys.Net.WebRequest.completed (ScriptResource.axd?d=k5RfMmPNK2hWIceXJ8-ajx3E8J_9Fwh_cmdsa2b8w5b_6SdxoV5CP7PTQYU2geZFptqlColfo4USOXQsdBih3W0VS_49yn_5vEAL69UdI91yC-tDiYJ5qy_HJzfGk6ituovIGh_kYQ43NWRInP8bleYrT4aM9uWrD_zUrKaOdVSegfYI0_gHDDpmP74zGEwh0&t=ffffffffecf19baa&ctag=200622:formatted:4336)
I would greatly appreciate help - thank you!!
<script>
function retrieveListItems(ID) {
var clientContext = new SP.ClientContext("https://xxxxxxx/DIG/Customer/");
var oList = clientContext.get_web().get_lists().getByTitle('Customer');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View>\
<Query>\
<Where>\
<Eq>\
<FieldRef Name='ID' />\
<Value Type='Counter'>"+ ID +
"</Value>\
</Eq>\
</Where>\
</Query>\
</View>");
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var color = new Object();
var oListItem = listItemEnumerator.get_current();
// Add Section wise set items here.
// Section 1
$("#selRequestType").val(oListItem.get_item('RequestType'));
$("#txtCustomerNumber").val(oListItem.get_item('CustomerNumber'));
var salesCont = (oListItem.get_item('ArdentSalesContact')).get_lookupValue();
$("#txtArdentSalesContact").val(salesCont);
var csr = (oListItem.get_item('CSR')).get_lookupValue();
$("#txtCSR").val(csr);
$("#txtAdditionalComments").val(oListItem.get_item('AdditionalComments'));
var company = oListItem.get_item('Company');
var companyArray = company.split('~');
for (var i = 0 ; i < companyArray.length; i++) {
$.each($("input[name='company']"), function () {
if ($(this).val() == companyArray[i]) {
$(this).prop('checked', true);
}
});
}
var OrderSystem = oListItem.get_item('OrderSystem');
OrderSystemArray = OrderSystem.split('~');
for (var i = 0 ; i < OrderSystemArray.length; i++) {
$.each($("input[name='OrderSystem']"), function () {
if ($(this).val() == OrderSystemArray[i]) {
$(this).prop('checked', true);
}
});
}
$("#selDoesExistInSFDC").val(oListItem.get_item('DoesLeadAccountExistInSFDC'))
;
$("#txtPasteURL").val(oListItem.get_item('PasteAccountURLFromSFDC'));
$("#txtParentNationalAccount").val(oListItem.get_item('ParentNationalAccount'));
$("#txtSoldToName").val(oListItem.get_item('SoldToName'));
$("#txtSoldToLegalName").val(oListItem.get_item('SoldToLegalName'));
$("#txtShortName").val(oListItem.get_item('ShortName'));
$("#selCustomerChannel").val(oListItem.get_item('CustomerChannel'));
//New field
var CustomerSegmentationField = oListItem.get_item('CustomerSegmentationField');
if (checkNotEmpty(CustomerSegmentationField)) {
$("#selCustomerSegmentationField").val(CustomerSegmentationField.get_lookupId());
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' +
args.get_stackTrace());
}
</script>
Does this cover that part?
The error mentions you have not loaded the field.
Make sure you loaded the item and the field static name matches ‘CustomerSegmentationField’
clientContext.load(listItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));

Ribbon Command to read values

My javascript is not the best and was wondering if someone could help me out with this. Essentially I have a library with an integer column called PGCount, I want to be able to click this button and it adds to the value of the defined variable pgcount, it is currently alert but I have greater plans for it, if only to get the desired results.
Sadly it is counting the first item twice.
Here is the whole module
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction
Id="Ribbon.Library.Actions.AddAButton"
Location="CommandUI.Ribbon"
RegistrationId="101"
RegistrationType="List"
Title="PGCount">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.Library.Share.Controls._children">
<Button Id="Ribbon.Library.Share.NewRibbonButton"
Command="CountPGCount"
LabelText="Page Count"
TemplateAlias="o2" />
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler Command="CountPGCount"
CommandAction="javascript:
var listitem;
var pgcounts = 0;
getWebProperties();
function getWebProperties() {
var ctx = new SP.ClientContext.get_current();
var currentWeb = ctx.get_web();
var currentListGuid = SP.ListOperation.Selection.getSelectedList();
var currentList = currentWeb.get_lists().getById(currentListGuid);
var selectedItems = SP.ListOperation.Selection.getSelectedItems();
for (i in selectedItems) {
listitem = currentList.getItemById(selectedItems[i].id);
ctx.load(listitem);
ctx.executeQueryAsync(Function.createDelegate(listitem, function () {
var c = listitem.get_fieldValues().PGCount;
pgcounts+=c;
}), null);
};}
setTimeout(function () {
alert(pgcounts);
}, 3000);"
EnabledScript="javascript:SP.ListOperation.Selection.getSelectedItems().length >= 1;" />
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
<Module Name="Module1">
</Module>
</Elements>
Any help would be appreciated!
Well I must say I am trilled to bits after working with this all day!
That is not counting the same issue experienced with similar projects as this load multiple items. A conflict always occurs.
Now I know a lot of you cool java heads are gonna say that's wrong here and there and I know that, especially checking the item counts and so on, but I don't think it is too shabby and it will I know help someone. Do feel free to tidy up the code if willing :)
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction
Id="Ribbon.Library.Actions.AddAButton"
Location="CommandUI.Ribbon"
RegistrationId="101"
RegistrationType="List"
Title="PGCount">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.Library.Share.Controls._children">
<Button Id="Ribbon.Library.Share.NewRibbonButton"
Command="CountPGCount"
LabelText="Page Count"
TemplateAlias="o2" />
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler Command="CountPGCount" CommandAction="javascript:
var rows = new Array();
var countofitems = -1;
var countogpgcounts = 0;
getpgcounts();
function getpgcounts() {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var lists = web.get_lists();
var listId = SP.ListOperation.Selection.getSelectedList();
var list = lists.getById(listId);
var selectedItems = SP.ListOperation.Selection.getSelectedItems();
rows = [];
for (var i in selectedItems) {
var id = selectedItems[i].id;
rows[i] = list.getItemById(id);
context.load(rows[i]);
countofitems++;
}
context.executeQueryAsync(Function.createDelegate(this, show),Function.createDelegate(this, showError));
}
function show() {
for (i in rows) {
var thiscount = rows[i].get_item('PGCount');
countogpgcounts += thiscount;
if (i == countofitems) {
alert(countogpgcounts);
}
}
}
function showError(sender, args) {
throw new Error('request failed: ' + args.get_message() + '\n' + args.get_stackTrace());
}
"
EnabledScript="javascript:SP.ListOperation.Selection.getSelectedItems().length >= 1;" />
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
<Module Name="Module1">
</Module>
</Elements>

Get items, changed by current user, via JSOM

In SharePoint 2013 JavaScript, I want to load all items from a list, that have been modified by the current user. I tried this:
var ctx = SP.ClientContext.get_current();
var settings = ctx.get_web().get_lists().getByTitle('My Setting List');
var settingQuery = new SP.CamlQuery();
settingQuery.set_viewXml('<Query><Where><Eq><FieldRef Name="Editor" LookupId="TRUE" /><Value Type="Integer"><UserID /></Value></Eq></Where></Query>');
var settingItems = settings.getItems(settingQuery);
ctx.load(settingItems, 'Include(Id, Title)');
ctx.executeQueryAsync( /* ... */ );
But it gives me all the items from all users. What did I do wrong?
SP.CamlQuery.viewXml Property expects XML schema to be specified in the following format:
<View>
<Query>
...
</Query>
</View>
So, the solution is to enclose your query using View element.
Example
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var qry = new SP.CamlQuery();
qry.set_viewXml('<View><Query><Where><Eq><FieldRef Name="Editor" LookupId="TRUE" /><Value Type="Integer"><UserID /></Value></Eq></Where></Query></View>');
var items = list.getItems(qry);
ctx.load(items, 'Include(Id, Title)');
ctx.executeQueryAsync(
function() {
console.log(items.get_count());
},
function(sender,args){
console.log(args.get_message());
});

Retrieving Start/End Time fields with SharePoint Client Object Model

I have some experience using the SharePoint Client Object Model to retrieve text fields and URLs/images from lists in SP 2013. I'm currently trying to do something similar with a calendar. I have been able to successfully retrieve Title and Location fields without any issue, but the Start and End Time fields I am not able to retrieve. I cannot figure out what exactly the issue is. Additionally, I can read Created and Modified with no problems. Here is the relevant code:
function retrieveListItemsCal() {
var clientContextCal = new SP.ClientContext.get_current();
var oListCal = clientContextCal.get_web().get_lists().getByTitle('Calendar');
var camlQueryCal = new SP.CamlQuery.createAllItemsQuery();
AllItemsCal = oListCal.getItems(camlQueryCal);
clientContextCal.load(AllItemsCal);
clientContextCal.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededCal), Function.createDelegate(this, this.onQueryFailedCal));
}
function onQuerySucceededCal(sender, args) {
var listItemInfo = '';
var listItemEnumeratorCal = AllItemsCal.getEnumerator();
var htmlCal = '';
htmlCal+="<div id='CalHeader'>Upcoming Events</div>\
<div id='CalDivider'></div>\
<div id='CalContainer'>";
while(listItemEnumeratorCal.moveNext()) {
var oListItemCal = listItemEnumeratorCal.get_current();
/*htmlCal+="<div class='CalItem'>\
"oListItemCal.get_item('Start Time')"\
</div>";*/
alert(oListItemCal.get_item("Start Time").format("MMMM d, yyyy"));
}
htmlCal+="</div>";
$("#CalSpace").append(htmlCal);
}
function onQueryFailedCal(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
$(document).ready(function(){
SP.SOD.executeFunc("sp.js", "SP.ClientContext", retrieveListItemsCal);
});
And here is a screenshot of the list columns: http://i.imgur.com/8IK4KTO.png
I have resolved my issue. I ran the following PowerShell queries (found here http://techtrainingnotes.blogspot.com/2012/10/sharepointfinding-column-display-and.html):
$web = Get-SPWeb SiteUrl
$list = $web.Lists["Announcements"]
$list.fields | select Title, InternalName, Hidden, CanBeDeleted | sort title | ft -AutoSize
The internal names of the Start Time and End Time fields are EventDate and EndDate, respectively.

Categories