Redirect from NewForm to DispForm or EditForm

Change log
July 29. 2013
I have fixed the code example as there were missing some backslashes for escaping quotes in a string. Thanks to Gary Poirier for alerting me.
03.03.2012
Updated the solution to use spjs-utility.js for compatibility with newer versions of jQuery. See download link below.
24.04.2011
I have added a few lines to take into account the dialog’s in SP2010.

I have done a few articles on this subject earlier, but here is another method which is simpler to use. What it does is to modify the form action in NewForm to redirect you to DispForm or EditForm after the form has been submitted. You are redirected without the ID parameter in the URL. When in DispForm or EditForm, the lack of an ID parameter triggers a query to find the last item added to the list by the current user.

This code examples refers jQuery from Google’s site. All other code is kept in the CEWP.

Note:
This example uses the parameter “_spUserId” which is provided by SharePoint and represents the logged in user’s ID. This code will not work for anonymous users.

Learn how to insert CEWP on NewForm, DispForm or EditForm

Start by adding this code in a CEWP below NewForm.aspx:

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

function PreSaveAction(){
	var URL = location.pathname.replace('NewForm.aspx','DispForm.aspx');
	if(GetUrlKeyValue('IsDlg')==='1'){
		URL+="?IsDlg=1";
	}
	$("#aspnetForm").attr('action',location.pathname+"?Source="+URL);
	return true;
}

</script> 

This code will send you to “DispForm” when submitting the form. To have it redirect you to EditForm, replace “DispForm” with EditForm” in line 05.

In DispForm.aspx (or EditForm.aspx), add this code in a CEWP below the form:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="/YourLocalScriptRepository/spjs-utility.js"></script>
<script type="text/javascript">
// List GUID or list display name of the current list
var thisListGuid = '{A162F3E2-32D8-4CA2-B849-14879CDC5494}';

// This code runs only if the ID parameter is omitted
if(GetUrlKeyValue('ID')===''){
	var lastID = getLastItemID();
	if(lastID!==''){
		var newURL = location.pathname+"?ID="+lastID;
		if(GetUrlKeyValue('IsDlg')==='1'){
			newURL+="&IsDlg=1";
		}
		location.href=newURL;
	}
}

/********************************************
	Do not modify anything below this line
*********************************************/
function getLastItemID(){	
	var queryBuffer = [];
		queryBuffer.push("<Where><Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='User'>"+_spUserId+"</Value></Eq></Where>");
		queryBuffer.push("<OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>");
	var res = spjs_QueryItems({listName:thisListGuid,query:queryBuffer.join(''),viewFields:['ID'],rowLimit:1});
	if(res.count<0){
		alert("An error occurred. Most likely the parameter \"thisListGuid\" is wrong.");
	}else if(res.count>0){
		return res.items[0].ID;
	}else{
		return '';
	}
}
</script>

You find spjs-utility.js here. Ensure you get the latest version

If you prefer to use a local copy of jQuery, download it from here.

In line 05 you must provide the list GUID (recommended) or the display name of the current list. Learn how to find the list GUID

Ask if anything is unclear
Alexander

111 thoughts on “Redirect from NewForm to DispForm or EditForm”

    1. Hi,
      Yes, this will work for both 2007 and for 2010. One might want to include the “IsDlg=1” parameter in the redirect URL to stay in a dialog after redirect. I will update the code in a few minutes to add this.

      Alexander

  1. Hi,
    this script does not work for Contenttypes on NewForm to DispForm. Have you any Idea why not?
    I get also redirected to NewForm.
    Thx for your help.

    BTW :nice Script 🙂

  2. If found a solution for this problem by myself.

    function PreSaveAction(){
    var URL = location.pathname.replace(‘NewForm.aspx’,’DispForm.aspx’);
    var contenttype = GetUrlKeyValue(‘ContentTypeId’);
    var rootfolder = GetUrlKeyValue(‘RootFolder’);

    if(GetUrlKeyValue(‘IsDlg’)===’1′){
    URL+=”?IsDlg=1″;
    }

    if(!contenttype)
    {
    $(“#aspnetForm”).attr(‘action’,location.pathname+”?Source=”+URL);
    }
    else{

    $(“#aspnetForm”).attr(‘action’,location.pathname+”?Source=”+URL+”&RootFolder=”+rootfolder+”&ContentTypeId=”+contenttype);
    ;

    }

    return true;
    }

    1. Hi,
      Use something like this for the cancel button found in the form – the ribbon button is not addressed with this code

      // Edit the redirect on the cancel-button
      $('input[id$="GoBack"]').each(function(){
          $(this).click(function(){
      			STSNavigate("your custom page URL");
      	  })
      });
      

      Alexander

    2. Perfect, thanks, your a life saver! Here’s another one I’ve been researching for days and no luck yet! I am using modal dialogs and I would like the modal dialog to close when a newform/editform is saved. By default it redirects the user to the AllItems view of the list.

      Colin

    3. I’ve found ways to make it re-direct to another page, but I am looking to close the current modal dialog on form save to display the page underneath it.

      Colin

    4. SOLVED!!!! I just created a new page and put a CEWP in it with the javascript to close a modal dialog. Then using Source= in my hyperlink I directed to that page so that when the user saves/closes a form it directs them to that page which then runs the javascript to close the Modal Dialog.

      Would still love to see your approach at it though if you’ve got any ideas?

    5. Hi,
      Sorry for the late reply, but isn’t this the default behavior for a model dialog? – however, if you put a “Source” attribute in the URL, you will be redirected to that location when submitting the form.

      Alexander

  3. I have seen articles about this redirect on several blogs. Filtering by the current user adds a nice touch and makes it the cleanest solution I’ve seen so far. Bravo!

  4. Happy New Year!!!

    You are a life saver….I have used many of your solutions in my work. You are fantastic….I have been a silent reader all this while…today you saved me again….This time I must stop and express my gratitude.

    Using your above solution I was able to redirect to a custom page in Survey that has page separation. when you click Next in the Survey Form, the Source parameter is lost. Using your solution I have been able to solve this. Thanks a zillion for sharing all these wonderful tips and tricks. No words to express my gratitude…

    Wish you and your loved ones a prosperous and healthy New Year…

    Lavanya.

  5. Hi Alexander. Thanks for this blog post. But I cant seem to make it work in my form. It’s not returning any result count/query is not returning any result. My list GUID is correct. I did not change any code. What do you think could be the problem? Should the viewName, pagingInfo be passed too when calling spjs_QueryItems function?

    Thank you! 😀

    1. Hi,
      Sorry for the late reply.

      I suspect your jQuery version is to new as there are compatibility issues with v1.7x.

      Try using jQuery v1.6.4.

      Alexander

  6. Hi Alexander, Thanks for the awesome post.
    I have a doc library test1,test2,test3.
    So when i add an item in test1 and click save,it will open the edit form of test2 for last item created and from there it should open the edit form of test3. everything works fine. but when i wrote the redirect code under presaveaction of editform(test2), the item is created twice in test2. So instead of editing the last created item, it creates new data and going to edit form of test3. So it duplicates.

    Could you please advise me on this.

    Thanks,
    Viji

    1. I guess there is an error in the “?” and “&” combination of the redirect URL.

      The new item created is in fact a folder(?) which is created when you have the wrong URL.

      Post the URL you are using (you may strip away the part before EditForm.aspx) and I’ll look at it.

      Alexander

    1. When saving an item in EditForm.aspx you need to have the ID in the “aspnetForm-action”.

      Try something like

      $("#aspnetForm").attr('action',location.pathname+"?ID="+GetUrlKeyValue('ID')+"%26Source="+URL);
      

      Alexander

  7. Hi Alexander,
    thanks for this great post! 🙂
    I just would like to know if someone solved the issue, that the code does not work with newer jquery versions. I can’t use an older version.
    If someone solved that, it would be great to know what’s that problem.
    thanks!

  8. Hi Alexander,

    Is this code Office 365 compatible?
    I’m trying to implement it in my current Office 365 environment but still no success.

    Function getLastItemID() returns ‘ ‘ in my current situation.

    List Guid – checked
    Latest JQuery version – checked
    Latest spjs-utility.js – checked

    Any advise?

  9. Hi there,
    I’m having some problems with redirection from NewForm.aspx to DispForm.asp.

    If i click on “New Item” from a DispForm.aspx page the redirection works perfectly, but click on “New” from the AllItems.aspx of my list the new item is not saved and the redirection fails. Instead it will navigate me from NewForm.aspx?RootFolder=… to NewForm.aspx?Source=…

    1. I solved this issue using the following:

      function setOnSubmitRedir(redirURL){
      var action = $(“#aspnetForm”).attr(‘action’);
      var end = action.indexOf(‘&’);
      if(action.indexOf(‘&’)<0){
      newAction = action + "?Source=" + redirURL;
      }else{
      newAction = action.substring(0,end) + "&Source=" + redirURL;
      }
      $("#aspnetForm").attr('action',newAction);
      }

      function PreSaveAction(){
      var URL = location.pathname.replace('NewForm.aspx','DispForm.aspx');
      if(GetUrlKeyValue('IsDlg')==='1'){
      URL+="?IsDlg=1";
      }

      //alert(location.pathname+"?IsDlg=1&Source="+URL);
      //$("#aspnetForm").attr('action',location.pathname+"?IsDlg=1&Source="+URL);
      setOnSubmitRedir(URL);
      return true;
      }

    2. I solved this issue using the following:

       
      
      function setOnSubmitRedir(redirURL){
      var action = $("#aspnetForm").attr('action');
      var end = action.indexOf('&');
      	if(action.indexOf('&')<0){
      		newAction = action + "?Source=" + redirURL;
      	}else{
      		newAction = action.substring(0,end) + "&Source=" + redirURL;
      	}
      $("#aspnetForm").attr('action',newAction);
      }
      
      
      
      
      function PreSaveAction(){
      	var URL = location.pathname.replace('NewForm.aspx','DispForm.aspx');
      	if(GetUrlKeyValue('IsDlg')==='1'){
      		URL+="?IsDlg=1";
      	}
      	
      	//alert(location.pathname+"?IsDlg=1&Source="+URL);
      	//$("#aspnetForm").attr('action',location.pathname+"?IsDlg=1&Source="+URL);
      	setOnSubmitRedir(URL);
      	return true;
      }
      
      
      
    3. I solved this issue using the following:

      function setOnSubmitRedir(redirURL){
      var action = $("#aspnetForm").attr('action');
      var end = action.indexOf('&');
      	if(action.indexOf('&')<0){
      		newAction = action + "?Source=" + redirURL;
      	}else{
      		newAction = action.substring(0,end) + "&Source=" + redirURL;
      	}
      $("#aspnetForm").attr('action',newAction);
      }
      
      
      
      
      function PreSaveAction(){
      	var URL = location.pathname.replace('NewForm.aspx','DispForm.aspx');
      	if(GetUrlKeyValue('IsDlg')==='1'){
      		URL+="?IsDlg=1";
      	}
      	
      	//alert(location.pathname+"?IsDlg=1&Source="+URL);
      	//$("#aspnetForm").attr('action',location.pathname+"?IsDlg=1&Source="+URL);
      	setOnSubmitRedir(URL);
      	return true;
      }
      
      
  10. Hi Alex,

    I want to send the users to Dispform after they create a new ited or edit an existing item. The disp form can then send them to the list if they exit. Is this possible.

    Thanks,
    San

  11. Seems my redirect is failing. I am able to redirect from NewForm.apsx to EditForm.aspx, but see inputted in all my fields: ” field value”. I’ve tried jquery 1.6.4 with no luck.

    1. I get this error as well. I am able to redirect from NewForm to Dispform, but all the fields I have filled out, get the value “field value.” I am using jquery 1.7.1 and SP 2010

      1. Hi,
        Verify the variable “thisListGuid”, and the script “src” to jQuery and spjs-utility.js.

        Hit F12 in IE and look for errors in the “Console”.

        Alexander

      2. Thank you so much for the tip on Console errors in IE! The problem was not the variable “thislistGuid”, but the alert in the code:

        alert(“An error occured. Most likely the parameter “thisListGuid” is wrong.”);

        The double quotation marks inside the alert text was not interpreted as intended, and this fixed everything 🙂

      3. For those of you who ge this error you must change this line

        alert(“An error occured. Most likely the parameter “thisListGuid” is

        to

        alert(“An error occured. Most likely the parameter “+thisListGuid+” is

        notice the + signs around thisListGuid

        Alexander Please update your code example

  12. Hello Alexander

    how can I create a button in ribbon on edit form to save and redirect to display form?
    Or to redirect directly on save to display form?

    Thanks,

  13. Hello Alexander

    My forms are made in infopath, so you great solution seems not work for me, because the url configuration are diferent.

    Can you help me?

    Thanks,

  14. I cannot seem to get the editform.aspx page to redirect to dispform.aspx after submittal. Tried to edit from the main view as well as clicking edit from within the item, both return to the default list view of all items after edit changes are submitted instead of going to dispform.aspx. I have tried all the above fixes:

    – Tried 1.7.1 & 1.6.4
    – List GUID is in place
    – Latest spjs-utility.js release

    Setup:
    – Site is using SSL
    – 2010 SharePoint Server running a 2007 Theme
    – spjs-utility.js util is on root site under “siteassets” folder (URL test works for me)

    thoughts?

  15. Hi Alex,

    i am using the latest of spjs-utility and the latest jquery… iv alsohave the correct GUID listname.. but otherwise in the dispform i am unable to pick up the answers made in the survey.. e.g. place visited: Ontario (in newform) but when i click on finish on the dispform it says (alaska).. what am i doing wrong here i have put in the correct codes in newform and dispform as well as their locations (beneath)

  16. Alex,

    Thank you for the great instructions. I tried setting up a survey with a custom form of branching using your instructions but I keep getting an object expected error at line $(“#aspnetForm”).attr(‘action’,location.pathname+”?Source=”+URL); Any ideas?

    Thank you,
    Dan

      1. Thank you for the reply. My problem was twofold, first my reference was wrong second, I did not check in the jQuery file after I imported it to the SiteAssets directory. Thanks again, this post will be a tremendous help.

  17. Alex,

    I’m using this script in SharePoint 2013 and it seems as Dave in the comments mentioned Dispform.aspx shows only the first item in the list not the one that created, what are you thoughts on this, i tried Juery 1.7,1.6.4 with your latest spjs script.

  18. Hi,
    I am trying to implement it to redirect my newform to displayform.aspx. For some reason, when i save it on newform.aspx, it is again taking me to the newform.aspx only. I tried it with 1.7. js and also 1.6.4 jquery, neither one works.
    I am trying it out in SharePoint 2010.
    Any suggestions on how to troubleshoot this issue?
    Thanks.

  19. Hi, I am new to jquery and I have been asked to make a form as Display form (aka non editable) after choosing a choice “Inactive” from a field “Choice”…if i choose “Active”..only then can i edit the form. can you kndly help

    1. Sorry for the late reply. You can do this either by using DFFS or by putting this code in EditForm:

      if(location.pathname.match("EditForm.aspx") !== null){
        var status = getFieldValue("TheFieldInternalNameOfYourField");
        if(status === "Inactive"){
          alert("You cannot edit while inactive");
          location.href = location.href.replace("EditForm.aspx","DispForm.aspx");
        }
      }

      This code will prevent everybody from editing, so you might want to adapt the code to let some users edit it in the inactive state.

      Alexander

  20. I think what is proposed may help for me but I am not sure. I have been trying for several weeks to solve this problem.

    I have a site where technical documents are reviewed in consideration for publishing. I created a Survey so that we could capture metrics on the reviews. There are two sets of questions based on the branching of the first question. To prevent errors I “Respond to this survey” to select the proper answer and then I save it and then send the link to the reviewer in a Task. When the user gets it and they go to answer survey questions the get the following error.

    No Item exists at . It may have been deleted or renamed by another user.

    I can open them but no one else can. All the research I have done (many hours worth) indicate it has something to do with the DispForm.aspxID=. Everything says that I need to change the DispForm to something else but they don’t say how, or why. I need to find how to fix this easily as I have to do 3 to 6 of these surveys for each paper.

    I am not a programmer and the IT powers have this locked down so I need something I can do with minimal programming and no Sharepoint Designer.

    Will what you are proposing help and can you break it down a little for someone who is not a programmer but plays one in real life?

    1. This sound like the user you send this survey to does not have access to the item. Go to “Survey Settings” > “Advanced settings” and “Item-level Permissions” and ensure you have the “Create and Edit access: Create and edit all responses” selected.

      Alexander

      1. Actually the problem appears to be that our company uses something called TeamCenter Community which is a Siemens @^$$^&(&^(*&7u version of Sharepoint and it has a major bug in it. I checked my set ups with someone with a regular Sharepoint and I have the exact same settings and permissions that he has on his but mine does not work.

        We just tried to find another method to do what I needed.

        Thanks for your help though.

  21. Alexander, would you consider rolling this function into dffs? It would be awesome to have both in one package. It would be great if was customizable in these ways:

    – ability to redirect differently by form (NewForm, EditForm)
    – ability to specify where to redirect (DispForm, ListView, SitePage, etc.)
    – ability to specify different redirects by user group

    Thanks!

  22. I’m using this in 2013 and I cant get the new form to redirect. The edit form code is working fine if I load it manually. Any insight into what might be going on would be greatly appreciated.

  23. PreSaveAction does not work in SP 2013.

    And, if I try to force the change of action in form, it does not work either. Any idea?

    The DispForm script works fine!

    1. Hi,
      You can change the NewForm code like this:

      <script type="text/javascript">
      if(GetUrlKeyValue("Source") === ""){
      	var rUrlKey = "";
      	if(location.search.length === 0){
      		rUrlKey = "?Source=";
      	}else{
      		rUrlKey = "&Source=";
      	}
      	location.href = location.href+rUrlKey+location.pathname.replace('NewForm.aspx','DispForm.aspx');
      }
      </script>

      Add this to a CEWP above the form for better performance as this code will reload the page when the user opens the form without a Source attribute in the URL.

      Alexander

  24. This solution works fine as long as there are no errors in the Newform. If there are, the newform is redisplayed (with the error fields highlighted) however the quicklaunch appears in the NewForm as well.

  25. Works perfectly with the standard list forms (Newform.aspx, etc…), but I can’t get it to work when the list is using custom InfoPath. I have some validations/filters on fields that are required… Any thoughts on how to set it up to work with “newifs.apsx”? Seems to be running a different function on save. Any help would be appreciated!

    Love your work!

  26. This only redirects back to the list and not the new form. I am using SharePoint 2013 Online and opening NewForm.aspx in a modal. Would that make a difference?

  27. Hi Alex,

    I implemented this solution and I’m getting a “Save conflict” error when I try to save the edit form.

    My Scenario is slightly different.

    I have a custom edit form with Parent and child list( is a xsltlistview webpart inserted below data form webpart). when I add child details and save the parent form i’m getting “Save Conflict” error.

    Any suggestions/workaround much appreciated.

    1. Hi,
      Sorry for the late reply – unfortunately I cannot help you with customized forms. I do however think you can set the redirect in SPD if you already have modified the form there. I cannot tell you how to do it though.

      Alexander

  28. I have this redirecting to an display form, however all of the fields are showing as “field value” instead of the actual value. I have verified that the GUID is correct, and also the jQuery and spjs-utility paths are correct. I have ran the debugger, and it always fails at the var res = spjs_QueryItems({listName:thisListGuid,query:queryBuffer.join(”),viewFields:[‘ID’],rowLimit:1}); line. Do you have any idea what the solution is? I believe I have tried almost everything listed in the comments above. Thanks in advance.

    1. What you describe is due to the fact that you do not have an ID parameter in the URL. Bring up the developer console by hitting F12 and selecting “Console”. Reload the page and report back the error message.

      Alexander

      1. I don’t know what the issue was, but it worked first thing today without making any changes. I have this working now with Infopath forms and doing a direct link to the New Form, following your instructions above. However, if I try to use the add new items on either the ribbon or at the bottom on the list it doesn’t work. Also, it doesn’t work when the form is opened in dialog mode. Do you know of the methods to get this to work? Thanks in advance.

  29. Thankyou for the great post! Works fine except one small hitch – When I redirect from Add to View page, the page loads twice :
    1. For the first load, plain DispForm.aspx is uploaded without any data in the field placeholders
    2. Loads againa after few split seconds – with all the list item data this time.
    How can this be corrected? Thanks in advance for the help.

    1. Hi,
      Unfortunately, this is how it works. The redirect sends you to DispForm without the ?ID=XX in the URL, this triggers a query to find the latest item added by the current user, and it then redirects to the proper item.

      You could try to hide the form if the ID is not found – something like this (snippet from the code example in the article):

      if(GetUrlKeyValue('ID')===''){
        // This will hide the form web part
        $("#part1").hide();
      
        // existing code her
      }

      Alexander

  30. Hi Alexander Bautz,

    Is it work for First time users of the list??
    If the list does not have any items with new users, will it work??

    Regards,
    Dileep.

  31. Hi Alex,

    I’ve tried to get this to work so that saving my EditForm.aspx stays on that edit form, but it always brings me back to my default list view.

    I’ve checked I’m using the right list ID. I’m also using DFFS in a modal for my forms, could this be causing the issue?

  32. Yes, modal dialogs will close when saving. Redirects are hard to get right, but if you want to redirect to the same editform, my best bet is to add a line of code that reloads the form with ?Source=/Site/Lists/ListName/EditForm.aspx?ID=TheID in the URL.

    This will cause a refresh of the page, but if you add this code to the top of the form (in a CEWP) it will not be that “heavy”.

    Alexander

    1. Just curious where I would add this? Just find a way to work it into the existing variable? Or would I need to make a whole new function? Sorry, bit of a JS noob.

  33. Okay, I made some progress, it’s at least attempting the script now. But sharepoint returns an error:

    Here’s my CEWP code below (I might’ve misinterpreted how to do this):

    function PreSaveAction(){
    var URL = location.pathname.replace(‘NewForm.aspx’,’EditForm.aspx’);
    if(GetUrlKeyValue(‘IsDlg’)===’1′){
    URL+=”?IsDlg=1″;
    }
    $(“#aspnetForm”).attr(‘action’,location.pathname+”?Source=”+URL);
    return true;
    }

    // List GUID or list display name of the current list
    var thisListGuid = ‘{14529BE3-F2E0-423A-806E-687C13EBE95A}’;

    // This code runs only if the ID parameter is omitted
    if(GetUrlKeyValue(‘ID’)===”){
    var lastID = getLastItemID();
    if(lastID!==”){
    var newURL = location.pathname+”?ID=”+lastID;
    if(GetUrlKeyValue(‘IsDlg’)===’1′){
    newURL+=”&IsDlg=1″;
    }
    location.href=newURL;
    }
    }

    /********************************************
    Do not modify anything below this line
    *********************************************/
    function getLastItemID(){
    var queryBuffer = [];
    queryBuffer.push(“<Where><Eq><FieldRef Name=’Author’ LookupId=’TRUE’ /><Value Type=’User’>”+_spUserId+”</Value></Eq></Where>”);
    queryBuffer.push(“<OrderBy><FieldRef Name=’ID’ Ascending=’FALSE’ /></OrderBy>”);
    var res = spjs_QueryItems({listName:thisListGuid,query:queryBuffer.join(”),viewFields:[‘ID’],rowLimit:1});
    if(res.count<0){
    alert(“An error occurred. Most likely the parameter \”thisListGuid\” is wrong.”);
    }else if(res.count>0){
    return res.items[0].ID;
    }else{
    return ”;
    }
    }

  34. Sorry, made the comment readable this time, you can delete the old one.

    Okay, I made some progress, it’s at least attempting the script now. But sharepoint returns an error:

    A file or folder with the name http://xxxxx/xxx/xxx/Restricted Area/Lists/PerformanceMeasurement/PM200038 already exists.

    Here’s my CEWP code below (I might’ve misinterpreted how to do this):

    function PreSaveAction(){
    var URL = location.pathname.replace(‘NewForm.aspx’,’EditForm.aspx’);
    if(GetUrlKeyValue(‘IsDlg’)===’1′){
    URL+=”?IsDlg=1″;
    }
    $(“#aspnetForm”).attr(‘action’,location.pathname+”?Source=”+URL);
    return true;
    }

    // List GUID or list display name of the current list
    var thisListGuid = ‘{14529BE3-F2E0-423A-806E-687C13EBE95A}’;

    // This code runs only if the ID parameter is omitted
    if(GetUrlKeyValue(‘ID’)===”){
    var lastID = getLastItemID();
    if(lastID!==”){
    var newURL = location.pathname+”?ID=”+lastID;
    if(GetUrlKeyValue(‘IsDlg’)===’1′){
    newURL+=”&IsDlg=1″;
    }
    location.href=newURL;
    }
    }

    /********************************************
    Do not modify anything below this line
    *********************************************/
    function getLastItemID(){
    var queryBuffer = [];
    queryBuffer.push(“<Where><Eq><FieldRef Name=’Author’ LookupId=’TRUE’ /><Value Type=’User’>”+_spUserId+”</Value></Eq></Where>”);
    queryBuffer.push(“<OrderBy><FieldRef Name=’ID’ Ascending=’FALSE’ /></OrderBy>”);
    var res = spjs_QueryItems({listName:thisListGuid,query:queryBuffer.join(”),viewFields:[‘ID’],rowLimit:1});
    if(res.count<0){
    alert(“An error occurred. Most likely the parameter \”thisListGuid\” is wrong.”);
    }else if(res.count>0){
    return res.items[0].ID;
    }else{
    return ”;
    }
    }

  35. Hi there

    I thought I had this working, but the Edit form doesn’t display any of the values I entered in the New form.

    Does the code get placed above or below the DFFS Frontend CEWP?

    I tried the console tip, but it seems to contain a large number of errors.

    Any ideas?

    Thanks

    Gerry

    DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
    File: POOverview.aspx
    HTML1300: Navigation occurred.
    File: POOverview.aspx
    HTML1202: https://moss.strath.ac.uk/celcis/Lists/ProjectRegister/POOverview.aspx is running in Compatibility View because ‘Display intranet sites in Compatibility View’ is checked.
    File: POOverview.aspx
    SEC7115: :visited and :link styles can only differ by color. Some styles were not applied to :visited.
    File: POOverview.aspx
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 20, Column: 1
    SCRIPT70: Permission denied
    File: uosmeta.js, Line: 17, Column: 11172
    SCRIPT70: Permission denied
    File: jquery.min.js, Line: 2, Column: 4457
    SCRIPT70: Permission denied
    File: browsertools.library.js, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: jquery-ui.min.js, Line: 6, Column: 73
    SCRIPT70: Permission denied
    File: jquery.SPServices.min.js, Line: 21, Column: 1
    SCRIPT70: Permission denied
    File: knockout.js, Line: 7, Column: 56
    SCRIPT70: Permission denied
    File: jquery.SPWidgets.min.js, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: spjs-utility.js, Line: 220, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 60, Column: 2
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 106, Column: 1
    SCRIPT70: Permission denied
    File: WebResource.axd, Line: 218, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 143, Column: 1653
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 302, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 597, Column: 9
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 846, Column: 2
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 930, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4079, Column: 10
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4166, Column: 4
    SCRIPT70: Permission denied
    File: jquery.min.js, Line: 2, Column: 6157
    SCRIPT70: Permission denied
    File: spjs-utility.js, Line: 24, Column: 1
    SCRIPT70: Permission denied
    File: eval code (147), Line: 1, Column: 263
    SCRIPT70: Permission denied
    File: eval code (148), Line: 1, Column: 275
    SCRIPT70: Permission denied
    File: eval code (149), Line: 1, Column: 497
    SCRIPT70: Permission denied
    File: browsertools.library.js, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: browsertools.library.js, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4314, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4363, Column: 17
    SCRIPT5007: Unable to get property ‘elements’ of undefined or null reference
    File: WebResource.axd, Line: 222, Column: 5
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4405, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4405, Column: 227
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4405, Column: 419
    SCRIPT70: Permission denied
    File: browsertools.library.js, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4409, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4448, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4451, Column: 3282
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4472, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4485, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4496, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4504, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4505, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4506, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4507, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4508, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4509, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4510, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4511, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4512, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4513, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4514, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4515, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4516, Column: 32
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4517, Column: 32
    SCRIPT5007: Unable to get property ‘submit’ of undefined or null reference
    File: NewForm.aspx, Line: 4521, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 4468, Column: 76
    SCRIPT70: Permission denied
    File: browsertools.library.js, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: browsertools.library.js, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: browsertools.library.js, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: browsertools.library.js, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 72, Column: 76
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 1, Column: 1
    SCRIPT70: Permission denied
    File: NewForm.aspx, Line: 1, Column: 1
    HTML1114: Codepage unicode from (UNICODE byte order mark) overrides conflicting codepage windows-1252 from (13)
    File: EditForm.aspx
    HTML1114: Codepage unicode from (UNICODE byte order mark) overrides conflicting codepage windows-1252 from (13)
    File: EditForm.aspx
    HTML1114: Codepage unicode from (UNICODE byte order mark) overrides conflicting codepage windows-1252 from (13)
    File: EditForm.aspx
    HTML1114: Codepage unicode from (UNICODE byte order mark) overrides conflicting codepage windows-1252 from (13)
    File: EditForm.aspx
    SCRIPT1002: Syntax error
    File: EditForm.aspx, Line: 4251, Column: 2
    SCRIPT5009: ‘PublishingRibbonUpdateRibbon’ is undefined
    File: EditForm.aspx, Line: 4544, Column: 1

    1. I suspect you are missing the ID parameter. Look at the URL – does it look like this:
      /EditForm.aspx?ID=[the ID of the element]

      If the ID number is missing, you must look at the DispForm code and try to figure out why the ID is not picked up.

      Alexander

  36. Hi Alex. This is my contribution for this solution. Is not a stable version, but this is a reducing the necessity to insert in both forms, only on NewForm.aspx.

    var listTitle = “Reposio Agenda”;//Change your list name
    var thisListGuid = _spPageContextInfo.pageListId;

    function dffs_PreSaveAction(){
    var lastID = getLastItemID();
    var redirectUrl = _spPageContextInfo.siteAbsoluteUrl + “/Lists/” + listTitle +”/DispForm.aspx?ID=” + lastID;
    WPQ2FormCtx.RedirectInfo.redirectUrl = redirectUrl;
    }

    function getLastItemID(){
    var queryBuffer = [];
    queryBuffer.push(“”);
    var res = spjs_QueryItems({listName:thisListGuid,query:queryBuffer.join(”),viewFields:[‘ID’],rowLimit:1});
    if(res.count0){
    return (parseInt(res.items[0].ID)+1);
    }else{
    return ”;
    }
    }

    1. Thanks, this looks good, but there is a small chance that someone other than you actually gets the next ID if they save at the exact same time, causing you to be redirected to the wrong list item.

      Alexander

  37. Error: _spUserId no longer exists in SharePoint 2013
    Switched to: _spPageContextInfo.userId works great!

    This was changed in the JS function getlastItemID()

  38. Is there a way to get the code to work by clicking a link or button (or Custom Action button) on the EditForm to redirect to the DisplayForm?

    1. I apologize for asking this again, and for not being clear the first time. I would like to use your code to go from the edit form to the display form. I would also like to trigger the action using something other than the Save button (a second button called Save As). When in install your code, instead of updating the edit form, it creates a new item in the list with the new info. Is there any way to get it to go from edit to display only editing the existing item?

      1. Hi,
        I’m not sure I understand what you want to achieve, but if you want to use “custom code” to save the form, you must get all values in the current form, wrap them up in an object form with FieldInternalName as “key” and the value as “value” like described here (for NewItem): https://spjsblog.com/2015/10/13/redirect-from-newform-to-editform-in-dffs/

        But instead of “spjs.utility.addItem” use “spjs.utility.updateItem” – and include one more parameter “id”:

        editItem = spjs.utility.updateItem({"listName":_spPageContextInfo.pageListId,"id":GetUrlKeyValue("ID"),"data":data});

        Alexander

  39. I’m not sure I understand what you want, but this code will redirect you from EditForm to DispForm:

    location.href = location.href.toLowerCase().replace("editform.aspx","dispform.aspx");

    Hope this help you on the way.

    Alexander

  40. It is possible to get this working with putting your code in the Custom JS tab in DFFS on both the New and Edit form? I’ve tried and it doesn’t seem to work.

  41. Below code is work for me

    1) On Save button of NewForm.aspx redirect to EditForm.aspx with newly created ItemId (NewForm and EditForm are List Forms)

    Let’s say list name is Project Profiles
    Solution :

    Download jquery-1.7.1.min.js and upload it into Scripts folder

    Create Text File Named PostSaveOnNewForm.txt
    Write below code on this Text file :

    var curURL = location.href;

    if (curURL.indexOf(“EditForm.aspx”) == -1)
    {
    var URL = location.pathname.replace(‘NewForm.aspx’,’EditForm.aspx’);
    if(GetUrlKeyValue(‘IsDlg’)===’1′){
    URL+=”?IsDlg=1″;
    }

    location.href = location.pathname+”?Source=”+URL;
    }

    Now Upload this Text file (PostSaveActionNewForm.txt) in
    Content types -> Style Library ->Scripts ->Files -> Upload Document

    Add below content editor web part on NewForm.aspx page , below the form.
    How to add this CEWP on page ?
     Go to list view ie. /Lists/Project%20Profiles/AllItems.aspx
     Click on new item
     Click on edit page
     Add a Web Part
     Media and Content
     Add
     Edit Web part
     Add text file Url in Content Link Box like
     (eg. /Style Library/Scripts/PostSaveActionNewForm.txt)
     Click on Layout -> Zone Index -> 3
     Here we write zone index 3 because we want our web part below the form
     And zone index of form is by default 2.
     Click on apply -> Ok
     Now Our Code is ready to redirect to EditForm.aspx
     Go to list Project Profiles -> New Item ->
     Save
     Now page will redirect to EditForm.aspx
    Download latest spjs-utility.js and Upload in Scripts folder
    We have to add CEWP on EditForm.aspx for redirect to EditForm.aspx?ID= with newly added ItemId
    Create Text File PostSaveActionEditForm.txt
    Add below Code :

    var itemId;
    // This code runs only if the ID parameter is omitted
    if(GetUrlKeyValue(‘ID’)===”){
    getLastItemId();
    }
    function getLastItemId()
    {

    var userId = _spPageContextInfo.userId;
    var caml = “”
    + “”
    + userId + “”
    + “”
    + “1”;
    var ctx = SP.ClientContext.get_current()
    var web = ctx.get_web()
    var list = web.get_lists().getByTitle(“Project Profiles”)
    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();
    itemId = item.get_id();

    // Navigate to EditForm with newly added Item Id

    if(itemId!==”)
    {
    var newURL = location.pathname+”?ID=”+itemId;
    if(GetUrlKeyValue(‘IsDlg’)===’1′)
    {
    newURL+=”&IsDlg=1″;
    }
    location.href=newURL;
    }

    }, function() {
    //failure handling comes here
    alert(“failed”);
    });
    }

     Upload this script file into Scripts Folder
     Then add CEWP in EditForm.aspx
     EditForm.aspx->Edit Page->
     Add web part->media and content->Add
     Edit web part -> Add text file Url in Content Link Box like
     (eg. /Style Library/Scripts/PostSaveActionEditForm.txt)
     Click on Layout -> Zone Index -> 1
     Here we write zone index 1 because we want our web part above the form
     And zone index of form is by default 2.
     Click on apply -> Ok
     Now Our Code is ready to redirect to EditForm.aspx with newly created itemId
     Go to list Project Profiles -> New Item ->
     Save
     Now page will redirect to EditForm.aspx?ID=1
     1 is just example ie. new item id

    Best of luck !!!

  42. How do I enable this functionality to work properly with DFFS enabled display forms? The javascript embedded in the CEWP is overriding my DFFS settings, causing unwanted behavior/formatting.

    1. I’m not sure I understand what you mean, but I have made a change in DFFS to prevent the “Source” from always being set back to the current dispform – when using NON DIALOG forms (option in the Misc tab). I will post this during the weekend.

      Alexander

  43. Hi there

    I’m upgrading to the my install of the DFFS solution and all is going well expect the redirect code which was working fine until the change. I’ve set the list to not open items in dialog so I can see the URL.

    When clicking the Save button I get the Newform reloaded with the values entered still there but I now have three buttons, Save, Edit and Cancel. Clicking on the Save button again I get an message saying [DFFS] Missing ID parameter for the list item in the URL. When I click the OK button the display form loads with the correct item ID in the URL.

    So it works, but I don’t know how to get rid of the message or what is causing it.

    Regards

    Gerry

  44. I’m not sure what this is. Can you bring up the dev console (hit F12 > Console) and post any errors from here?

    If you don’t see any errors there, post the URL from the form after your first save. You can change the domain name to “contoso.com” so you don’t reveal it.

    Alexander

    1. Sorry for the delay. Other priorities for a bit.

      The alert is still showing, but it seems that it is appearing before the code has had a change to complete its job. After clicking the OK button on the alert, the display form with the correct item is loaded, so the code works – when it gets a chance to finish. Is there a way of delaying execution or suppressing the alert once I know it works?

      Gerry

  45. Hi,
    The alert has been changed to a single line of text informing about the missing ID in the url in one of the latest versions (currently v4.365 is latest).

    If the code works and redirects you after you click the “OK” button in the alert, you might get it working by loading the latest version.

    PS: I have described an alternate redirect option here: https://spjsblog.com/2015/10/13/redirect-from-newform-to-editform-in-dffs/

    Alexander

  46. It sounds like some users were able to get this code functioning in SP2013 with minor changes. Is that correct? If so will using PreSaveAction/PreSaveItem conflict with DFFS?

      1. SharePoint has some built in functions that will not be overridden by this approach when using dialogs.

        Unfortunately I still haven’t figured out a good method to fix this (without adding code to the master page).

        If anyone has a fix for handling custom redirects in SP 2013 I would love to hear about it.

        Alexander

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.