Three ways to get the id of last created SPListItem
By Anatoly Mironov
An interesting question came on SharePoint StackExchange: How to retrieve the guid of the last uploaded file. It is only possible in CSOM as far as I know. But if we simplify the task, how to get the id of the last item, the we can compare three ways of getting them: SPServices, jQuery + listdata.svc and CSOM.
SPServices
The most easiest way, but not available in async:
$().SPServices.SPGetLastItemId({
listName: "Documents"
});
listdata.svc
Just combine some query strings and try in the browsers address bar:
http://dev/\_vti\_bin/listdata.svc/Documents()?
$filter=CreatedById eq 1
&$orderby=Created desc
&$top=1&$select=Id
CSOM
Not so easy to get started, but very powerful and you can get much more of information than with other methods.
function getLastItemId() {
var userId = \_spPageContextInfo.userId;
var caml = "<View><Query><Where>"
+ "<Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='Integer'>"
+ userId + "</Value></Eq></Where>"
+ "<OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>"
+ "</Query><RowLimit>1</RowLimit></View>";
var ctx = SP.ClientContext.get\_current()
var web = ctx.get\_web()
var list = web.get\_lists().getByTitle("Documents")
var query = new SP.CamlQuery();
query.set\_viewXml(caml);
var items = list.getItems(query);
ctx.load(items)
ctx.executeQueryAsync(function() {
// success actions
var count = items.get\_count();
//should only be 1
if (count > 1) {
throw "Something is wrong. Should only be one latest list item / doc";
}
var enumerator = items.getEnumerator();
enumerator.moveNext();
var item = enumerator.get\_current();
var id = item.get\_id();
// do something with your result!!!!
alert(guidString);
}, function() {
//failure handling comes here
alert("failed");
});
}
getLastItemId();
Comments from Wordpress.com
Rujal Jariwala - Jul 5, 2014
nice post…
[…] Three ways to get the id of last created SPListItem … – An interesting question came on SharePoint StackExchange: How to retrieve the guid of the last uploaded file. It is only possible in CSOM as far as I know. […]
very helpful, thank you. u saved my project.