none
Get ID of last item in sharepoint list using JSOM or CSOM RRS feed

  • Question

  • Hi

    the problem is i need the value last ID which was created in the list, whether the item is deleted or not

    whichever is the last id i need value if that as i am creating a sequential number using the ID

    Below is my code

    <html>
    <head>
    
    <script type="text/javascript"> 
     
        ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js"); 
       
        // Get the current Site
        var  webAbsoluteUrl;
        function retrieveListItems() {
            webAbsoluteUrl=  _spPageContextInfo.webAbsoluteUrl;
          
            if (_spPageContextInfo.serverRequestPath.endsWith("NewForm.aspx"))
    {       
            var clientContext = new SP.ClientContext(webAbsoluteUrl);
            // Get the liste instance
            var oList = clientContext.get_web().get_lists().getByTitle('ABC');
             
            var camlQuery = new SP.CamlQuery();
    
            // Get only the last element
            camlQuery.set_viewXml('<Query><OrderBy><FieldRef Name=\'Title\'  Ascending=\'False\' /></OrderBy></Query><RowLimit>1</RowLimit>');
            collListItem = oList.getItems(camlQuery);
    
            clientContext.load(collListItem);
    
            clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);        
    }
        
    }
        function onQuerySucceeded(sender, args) {
            $("input[id*='fa564e0f-0c70-4ab9-b863-0177e6ddd247']").attr("readonly", "true").css('background-color', '#fff', 'color', '#444');
            $("input[id*='fa564e0f-0c70-4ab9-b863-0177e6ddd247']").attr("disabled", "disabled");
            var isdata=false;
            var listItemInfo='';
            var listItemEnumerator = collListItem.getEnumerator();
            while (listItemEnumerator.moveNext()) {
    			isdata=true;
                var oListItem = listItemEnumerator.get_current();
    			 listItemInfo = oListItem.get_item("ID");
    			 
                // Split the first
                var res = listItemInfo;
    
    			var newID1 = res+1;
    			var newID = "ABC-00" + newID1
                // create the new id
    			if(isdata==true){
    			    $("input[id*='fa564e0f-0c70-4ab9-b863-0177e6ddd247']").val(newID);
    			}
    		
            }
    		if(isdata==false){
    			
    		    $("input[id*='fa564e0f-0c70-4ab9-b863-0177e6ddd247']").val("ABC-00" + 1);
    	  
    	   }
          listItemInfo.toString();
       
        }
        function onQueryFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); 
        }   
    	
    
    _spBodyOnLoadFunctionNames.push("SetReadOnly()");
    
    
    </script>
    </head>
    </html>
    	
    
        
    
    
    
    


    Paru

    Thursday, May 3, 2018 3:23 PM

All replies

  • Hi Paru,

    Try the below code, here the list name is Documents. Change it based on your list name.
    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(id);
    
        }, function() { 
            //failure handling comes here
            alert("failed"); 
        });
    }
    getLastItemId();


    Ramakrishnan


    Please remember to mark the replies as answers if they helped.


    Thursday, May 3, 2018 3:37 PM
  • Thanks Ramakrishnan

    Tried your code but it also gives the same result as mine,

    however this could help me with the issue

    https://www.epmpartners.com.au/blog/how-to-create-an-auto-incrementing-number-field-in-a-sharepoint-list/

    but the problem with this is user has to refresh the page to see the reflected changes which is not very friendly


    Paru



    Friday, May 4, 2018 10:50 AM
  • Hi Paru,

    from your question I understood that you need the latest item id from a list which the script provide.
    Kindly elaborate your requirement, since from the script your shared initially, I can see you need to generate a "ABC-00".

    Is this number to be generated on new form?
    if yes, Should the number is expected to be populated in a field of the new form?
    if yes, provide me the field internal name as well?

    Based on the information, I can provide a working script.


    Ramakrishnan


    Please remember to mark the replies as answers if they helped.



    Friday, May 4, 2018 11:00 AM
  • Sure Ramakrishnan

    Is this number to be generated on new form? - yes it is to be generated in new form

    if yes, Should the number is expected to be populated in a field of the new form? Yes

    if yes, provide me the field internal name as well? Title field

    and i do not want the latest item is id in the list want the ID of the item which was last created or deleted from the list, so the even if we restore the item this id do not duplicate.

    Please tell me if i am clear in elaborating the requirement?

    Thanks

    Paru


    Paru

    Monday, May 7, 2018 4:18 PM
  • Hi Paru,

    Add a CEWP or script editor webpart in the new form and insert below code.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="/_layouts/15/sp.runtime.js"></script>  
    <script src="/_layouts/15/sp.js"></script>  
    <script>
    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().getById(_spPageContextInfo.listId)
        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();
    		console.log(id.toString().length);
            // do something with your result!!!!
            switch(id.toString().length)
    		{
    		  case 0: $("input[id^='Title'").val("ABC-00"+id);break;
    		  case 1: $("input[id^='Title'").val("ABC-00"+id);break;
    		  case 2: $("input[id^='Title'").val("ABC-0"+id);break;
    		  case 3: $("input[id^='Title'").val("ABC-"+id);break;
                      default: $("input[id^='Title'").val("ABC-"+id);
    		}
    
        }, function() { 
            //failure handling comes here
            alert("failed"); 
        });
    }
    
    $(document).ready(function(){
    	getLastItemId();
    });
    </script>



    Ramakrishnan


    Please remember to mark the replies as answers if they helped.


    Tuesday, May 8, 2018 9:51 AM
  • Hi Paru,

    Any update in this regard. If it helped, then please mark the replies as answers.


    Ramakrishnan


    Please remember to mark the replies as answers if they helped.

    Wednesday, May 9, 2018 12:04 PM
  • This is close to what I am looking for, but isn't the CAML query only returning the last item the current user authored?
    Monday, March 4, 2019 3:01 PM