Get items, changed by current user, via JSOM - javascript

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

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

How to create an Enterprise custom field programmatically for Project Server

I want a Sharepoint 2013 app to create programmatically an Enterprise Custom Field when it runs for the first time.
I fiddled around with the following code snippet, but it's not working
var projContext = PS.ProjectContext.get_current();
function AddCustomField() {
$('#message').text('Adding Custom Field...');
var object_to_add = new PS.CustomFieldCreationInformation();
object_to_add.FieldType = CustomFieldType.Text;
object_to_add.Name = "New_one";
object_to_add.Description = "test description";
projContext.CustomFieldCollection.add(object_to_add);
}
Any help would be appreciated!
var projContext = PS.ProjectContext.get_current();
var fieldType = PS.CustomFieldType.TEXT;
var customfields = projContext.get_customFields();
var entityTypes = projContext.get_entityTypes();
var projEntity = entityTypes.get_projectEntity();
var resourceEntity = entityTypes.get_resourceEntity();
var taskEntity = entityTypes.get_taskEntity();
projContext.load(customfields);
projContext.load(entityTypes);
projContext.load(projEntity);
projContext.load(resourceEntity);
projContext.load(taskEntity);
projContext.executeQueryAsync(QuerySucceeded, QueryFailed);
CreateField("Test", "Test", fieldType, projEntity);
function CreateField(name, description, fieldtype, entitytype) {
var customfieldInfo = new PS.CustomFieldCreationInformation();
customfieldInfo.set_description(description);
customfieldInfo.set_name(name);
customfieldInfo.set_fieldType(fieldtype);
customfieldInfo.set_entityType(entitytype);
customfields.add(customfieldInfo);
customfields.update();
projContext.load(customfields);
projContext.executeQueryAsync(QuerySucceeded, QueryFailed);
}

how to pass data from one window to another in titanium (classic)?

'MyHTTPlink (mentioned in my code] consists some Restaurant Name, url, address. Using this code to i list all restaurant name and url in my table. Now I want to do, how to send the table row details to next window(.js page). The restaurant url consist lot of menu items for each restaurant. List the menu items in table row on next page. How to code that?'
var win = Titanium.UI.createWindow ({ backgorundColor: '#000'});
var tableview = Ti.UI.createTableView({
height:'auto',
layout:'vertical',
top:5,
right:5,
bottom:5, left:5 });
var data = [];
var xhr = Ti.Network.createHTTPClient ({
onload: function () {
alert("success!");
var json = JSON.parse(this.responseText);
for (var i = 0; i < json.connectionResponses.length; i++) {
var row = Ti.UI.createTableViewRow({
height: 60,
});
var restLabel = Ti.UI.createLabel({
text: json.connectionResponses[i].restaurantName,
height: 'auto',
left:54,
top: 5,
font:{ fontSize:20 }
});
var connLabel = Ti.UI.createLabel({
text: json.connectionResponses[i].connectingurl,
height: 'auto',
left:54,
bottom:5,
font:{ fontSize:14 }
});
var image = Titanium.UI.createImageView({
image:'images/menu_icon.png',
top:4,
left:0,
height:45,
width:41
});
row.add(restLabel);
row.add(connLabel);
row.add(image);
data.push(row);
}
tableview.setData(data);
},
onerror: function () {
alert('There was an error retrieving the remote data. Try again.');
}
//timeout:5000
});
xhr.open("GET", "http:MYHTTPlink");
xhr.send();
tableview.addEventListener('click',function(e){
//alert("RS Name : " +e.row.title);
var winn = Ti.UI.createWindow({ url:'hotelpage.js'});
winn.open();
//var hostelwin = require('hotelpage').gethotelWin;
//var newwin = new hotelwin();
//newwin.open();
});
win.add(tableview);
win.open();
Please just check below Code and use in your code.
you can perform your work like this.
tableview.addEventListener('click',function(e){
//alert("RS Name : " +e.row.title);
var winn = Ti.UI.createWindow({
url:'hotelpage.js',
row_title : e.row.title,
all_info: e.row,
});
winn.open();
//var hostelwin = require('hotelpage').gethotelWin;
//var newwin = new hotelwin();
//newwin.open();
});
and in "hotelpage.js"
var curtWind = Ti.UI.currentWindow;
// Get Data like this
var title = curtWind.row_title;
var allData = curtWind.all_info;
// and you can use as per your requirement.
May be this is Helpful for you,
Thanks,
In addition to what MRT answered that is correct and working, you could use this code that avoid the use of url property as recommended here: Titanium 3.X documentation
In your code:
tableview.addEventListener('click',function(e){
hotelWin = require('/yourpath/hotelpage');
var hotelW = new hotelWin(e.row.title, e.row.id)
});
In hotelpage.js
function external(title, id) {
var hotelPageWin = Titanium.UI.createWindow({
//properties here
});
//You have available here two variables:
//title with assigned the value of e.row.title
//id with assigned the value of e.row.id
hotelPageWin.open();
return hotelPageWin;
};
module.exports = external;

How do I get ID from an SPListItemCollection in 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.

Categories