2

I wanted to add a new ID on NewForm.aspx unfortunately that can't be done because a new ID has not actually generated yet. However, I thought maybe there is a way, by getting the current list's last ID and then adding +1 to it, thus giving me a supposedly new ID.

Is there a way to do this via javascript/jquery? I'm using this code in Content Editor webpart ViewForm/EditForm.aspx to get the current ID.

<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>

<script type="text/javascript">
   $(function() {
     // Get the ID from the query string
   var id = getQueryString()["ID"];

   // Find the form's main table
   var table = $('table.ms-formtable');

   // Add a row with the ID in
   table.prepend("<tr><td class='ms-formlabel'><h3 class='ms-standardheader'>ID</h3></td>" +
                 "<td class='ms-formbody'>" + id + "&nbsp;</td></tr>");
})

function getQueryString() {
  var assoc = new Array();
  var queryString = unescape(location.search.substring(1));
  var keyValues = queryString.split('&');
  for (var i in keyValues) {
    var key = keyValues[i].split('=');
    assoc[key[0]] = key[1];
     }
  return assoc;
}
</script>

Source: http://blog.pentalogic.net/2010/07/showing-the-records-id-on-the-view-and-edit-forms/

Using the same language above (jquery/ajax?) I'm hoping someone can help modify to add to the current table the "max(ID)+1" type of formula.

Your help is appreciated.

3 Answers 3

6

SUMMARY

This is maybe more complex than you may want, but it can be done. You also have a choice of using a hacky technique (read to the section break after the first code sample) or using the information in the first part to do some real work and re-create the item creation routine on your NewItem form.

As a disclaimer, I'm assuming that you're using SP 2013 since it wasn't specified!

Also, I'm pretty sure you'll need to move to a jQuery version newer than 1.3.2 to have the promises in my sample ajax calls work... I use 1.11.1, since I still have quite a few user on IE8.

Something like this:

<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>

You can get what the next item ID will be by using the REST or JavaScript Object Model APIs. I'll demonstrate with the REST API (note my example code uses the jQuery library):

function reserveListItemIdAsync() {
    return $.ajax({
        url: "/_api/web/lists/getByTitle('Test')/reserveListItemId",
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        }
    });
}

(function() {
    reserveListItemIdAsync().then(function(data) {
        var newItemId = data.d.ReserveListItemId;
        //do some other stuff with the returned item id here
        //note you may not have access to all of the DOM elements yet
    });
}());

This retrieves what would be the next ID to be submitted to the list, and increments whatever internal counter the list uses to the next available ID. You're actually changing the state of the list here -- hence the need to use the POST request to get this information.

Now from here you have a choice on what you want to do with this ID that was just returned to you...

If you really just want something simple, and you can guarantee that no previous items will ever be removed (good luck with that...) then you could take the value you just retrieved, add one to it, then when you hit submit on NewItem form you'll have the matching ID. I do really want to stress that this is pretty much a hack... but if you want to use that ID you just retrieved in the last step, you have to hijack the submission routine and basically build your own using whatever client-side API you're working with.


If you're still reading, I'll assume you interested in doing things at least somewhat correctly, and want to submit your item with that ID value you just retrieved.

There's no nice way to do this since you can't just serialize the form to submit it (there is no form element, and go ahead and try serializing the inputs and see what your key names look like!) So you'll need to manually get each element on the form and map it to its proper field. Since we started with the REST API, let's continue!

function addListItemWithReservedIdAsync(newItemId) {
    return $.ajax({
        url: "/_api/lists/getByTitle('Test')/items",
        type: "POST",
        data: JSON.stringify({
            '__metadata': {
                // NOTE: it's really SUPER IMPORTANT that you modify this 'type'
                // to match whatever list you're using, see MSDN for examples
                'type': 'SP.Data.TestListItem'
            },
            'Title': 'TestAdd',
            'Id': newItemId
        }),
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        }
    });
}

If you call the above function with that ID value you just fetched as a parameter, you'll create a list item with that ID. Where I have 'Title' and 'Id' is where you would need to add the rest of your field names and values. I mention it in comments in the code, but you'll need to change that type attribute as noted on the MSDN 'SharePoint 2013 REST Service - Working with lists and list items' page:

To do this operation, you must know the ListItemEntityTypeFullName property of the list and pass that as the value of type in the HTTP request body.

You can find this magical property by making a REST call against the list you're trying to write to.

This is a lot of information and there are quite a few places where you can go wrong, but you can use this general idea and reference the MSDN page above and it should get you headed in the right direction.

1
  • This looks amazing. I will try this out and keep you posted.
    – Humble Val
    Commented Aug 20, 2014 at 12:41
1

I asked similar question here Get List Item ID from NewForm.aspx

This link helped. http://spjsblog.com/2011/04/23/redirect-from-newform-to-dispform-or-editform/

0

I would provide a very straight forward approach. Just get the last ID of the list item by making SPService call and increment it by 1.

<script type="text/javascript" src="/YouSite/jquery.min.js"></script>
<script type="text/javascript" src="/YouSite/jquery.SPServices-2014.02.min.js"></script>  

<script language="javascript" type="text/javascript">
    $(document).ready(function() {   
        var researchFormList = "Request Form"; //Your List Name
        var requestIDField = "RequestID"; // Your ID field
        NewRequestID(researchFormList , requestIDField )
    });

    function NewRequestID(researchFormList , requestIDField  ) 
    {
        //query to retrieve all items
        var query = "<Query><OrderBy><FieldRef Name='RequestID' Ascending='False' /></OrderBy></Query>";
        //return fields for slide content and background picture
        var camlViewFields = "<ViewFields><FieldRef Name='"+requestIDField  +"' /></ViewFields>";

        $().SPServices
        ({
            operation: "GetListItems",
            async: true,
            listName: researchFormList,
            CAMLViewFields: camlViewFields,
            CAMLQuery: query,
            completefunc: function(xData, Status) 
            {  
                $(xData.responseXML).SPFilterNode("z:row").each(function() 
                { 
                    // Parsing double field to int
                    var requestID  = parseInt($(this).attr("ows_RequestID").replace("attribute[", "").replace("]", "")); 
                    var newRequestID = requestID  + 1; 
                    $('input[title="RequestID"]').val(newRequestID); 
                    return false;
                });  

                }
        }); // end SPServices call
     }

</script>  
1
  • This only works if your last item wasn't deleted and is visible by the current user.
    – Jeff
    Commented Nov 20, 2020 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.