Redirect from NewForm to EditForm or custom page

23.04.2011 Yet another article about the same topic can be found here

21.11.2009 A new article describing another method for redirecting a user to a custom page on “OK” and another page on “Cancel” is found here. This method is a good replacement for the “simple redirect” described in this article.

I have struggled a bit trying to redirect the user from NewForm to EditForm of the same list item – midway in filling the form. The reason i wanted to do this was to have access to the item ID when proceeding with the rest of the form fields (to make a relation between this list item and an item in another list).

I ended up using a brilliant solution called sessvars, from a guy named Thomas Frank. Read about it and get the sessvars.js here.

This technique can also be used to “redirect” the user to a custom “Thank you for participating…” – page after filling the form and clicking the “OK” button. I will provide examples of both methods.

In both examples you begin like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a subsite named “test” with a subsite named “English” with a document library named “Javascript”):
Img

A simple redirect from NewForm to a “Thank you for submitting” – page can be done like this.
Add a CEWP below the listform in NewForm and add reference to the scripts like this:

Img

The variable “sessvars.targetUrl” is set in a function called PreSaveAction which is always called when you click the “OK-button”. It must return true for the item to be saved. When this variable is set in this function, it is only set if the user actually saves the list item and not if the user clicks “Cancel”. this overcomes the problem with adding a ?Source=/test/English/ThankYou.aspx to the URL – which would redirect the user even if he clicks “Cancel”.
[javascript]
<script type="text/javascript" src="/test/English/Javascript/sessvars.js"></script>
<script type="text/javascript">
function PreSaveAction(){
sessvars.targetUrl = ‘/test/English/ThankYou.aspx’;
return true;
}
</script>
[/javascript]

Then you have to add a CEWP to the standard view of your list (the view you normally would be redirected to after saving a list item if you have no ?Source= in the query string of your URL):
Img

This code checks if the variable “sessvars.targetUrl” is defined, and redirects the user to the specified address. Note that right before the redirect, the variable is cleared with “sessvars.$.clearMem()”, to prevent the user from getting redirected multiple times.
[javascript]
<script type="text/javascript" src="/test/English/Javascript/sessvars.js"></script>
<script type="text/javascript">
var targetUrl = sessvars.targetUrl;
if(targetUrl!=undefined){
sessvars.$.clearMem();
window.location.href = targetUrl;
}
</script>
[/javascript]

When the user adds a new item to the list, he is redirected to the URL specified in the variable “sessvars.targetUrl” like this:
Img

A redirect from NewForm to EditForm can be done like this:
Like in the example above, add the necessary scripts:
Img

Here i have used some new scripts published on CodePlex by a user named DuWei. Get them here. I have used interaction.js and stringBuffer.js in this example.

Add a CEWP to the NewForm with this code:
Img

You have to provide the URL to EditForm.aspx, and the list GUID of the list.
[javascript]
<script type="text/javascript" src="/test/English/Javascript/sessvars.js"></script>
<script type="text/javascript">
function PreSaveAction(){
// SharePoint variable of current user’s id
sessvars.userId = _spUserId;
// Path of the list to redirect to – current list
sessvars.targetUrl = ‘/test/English/Lists/NewFormToEditFormRedirect/EditForm.aspx’;
// The BaseUrl of the site or subsite you are located
sessvars.listBaseUrl = L_Menu_BaseUrl; // SharePoint provides this
// List Guid of the list to redirect to
sessvars.listGuid = ‘{1791b3f2-9725-49fb-a8a4-561a57e38b34}’;
return true;
}
</script>
[/javascript]
Then you add a CEWP to the standard view of your list:
Img
[javascript]
<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/test/English/Javascript/interaction.js"></script>
<script type="text/javascript" src="/test/English/Javascript/stringBuffer.js"></script>
<script type="text/javascript" src="/test/English/Javascript/sessvars.js"></script>

<script type="text/javascript">
var userId = sessvars.userId;
var targetUrl = sessvars.targetUrl;
var listBaseUrl = sessvars.listBaseUrl;
var listGuid = sessvars.listGuid;

if(userId!=undefined && targetUrl!=undefined && listGuid!=undefined){
// Query to find the newest item added by current user
wsBaseUrl = listBaseUrl + ‘/_vti_bin/’;
var res = queryItems(listGuid,"<Where><Eq><FieldRef Name=’Author’ LookupId=’TRUE’/><Value Type=’Integer’>" + userId + "</Value></Eq></Where><OrderBy><FieldRef Name=’ID’ Ascending=’FALSE’/></OrderBy>",[‘ID’]);
// Gets the ID of the item
var itemId = res.items[0][‘ID’]; // This is the newest item added by current user
// Clears the session variables to prevent redirecting multiple times
sessvars.$.clearMem();
// Redirects the user to the correct item and opens it in EditForm
window.location.href = targetUrl + "?ID=" + itemId;
}
</script>
[/javascript]

When a user saves the list item – he is redirected to the EditForm (or DispForm if you specify it in the URL) of the list item he just added.

Please ask if something is unclear.
Alexander

60 thoughts on “Redirect from NewForm to EditForm or custom page”

  1. I ahve a sharepoint blog that i created with two additional required field for comments. if i apply this it does not seems to go throught he validation routine if a column is not filled out. it simple reidrect to the url with with no added item. Your help would be greatly appreaciated.
    Andy

  2. Which one of the methods are you using? – is it he “simple” redirect to a “thank you-page”?

    Remember that the actual redirect script is supposed to be placed in the default list view of your list (like AllItems.aspx) where you, by default, is redirected to after you add a list element.

    The only script to be added to your NewForm.aspx is the one setting the “sessvars.targetUrl value”:

    
    
    

    Alexander

  3. I hope you are willing to help a sharepoint newbie out.

    How were you able to add a web part to the new form? The image does not look like you used SharePoint designer. I have full control permissions and the “Edit Page” selection is grayed out when I navigate to the newform.aspx.

    I did try adding this in sharepoint designer, but I was not able to place the CEWB below the form, only beside it. After doing this, the solution did not work. But, the only place I added the desired URL for redirect is after the ?src. Was it supposed to go somewhere else as well?

    I could really use this functionality on one of my sites. If you can offer any advice, it’d be appreciated. Thanks for sharing!

  4. I have been able to get it to redirect to the edit page as directed above. However it does not retain any values that were entered on the new form. It saves the data just no actual data on the edit form, just place holders.

    The other issue is I need it to wait about 5 seconds before it opens the page. I have a workflow that needs to complete before it open,

    Please email me if you need any more specific informayion.

  5. Ok, I actually fixed the issue. I had added an additional ? after the ID. Now I have another issue, its running faster than my workflows. Is there a way to slow it down or to add a single refresh on the edit page.

    1. Hi,
      To achieve this you would have to have a looping function checking the status of the workflow, refreshing the page when the status i “Completed”.

      I have had a request for a function like this earlier, and I will write an article about it. I cannot promise a “delivery date”, but stay tuned…

      Alexander

  6. Is there a way to build a “pause” into the script for 1 or 2 seconds before the redirect occurs? This should give the workflow enough time to complete. We are attempting to move the item to another list and then open that new item in the edit form. Sometimes it works sometimes it does not because the workflow did not finish. So in those cases it opens the previous item I created.

  7. Works perfect now. With even added a little wrinkle to have it redirect to the edit form of another list. This is a great tool and I really appreciate your work and willingness to share.

    If you get bored and want to tackle another option. I am looking to create an option similar to what you have done, except instead of looking at who created the item and the last ID, I want a searcg based on the title field and then open that item in the edit sheet.

    Thanks to Marc Anderson, I have the script to let the user know that they have not entered an unique title (but have not been able to disable the OK button).

    Thank you again.

  8. From what I can tell, in SharePoint Designer you can just set the RedirectURL property of the button you’re trying to control the behavior on. For example, I just changed my Save button on a new item form to redirect to thankyou.aspx by putting the thank you page’s url in the RedirectURL property.

    In SPD, right-click the Save button and look at the Tag Properties. You’ll see RedirectURL as an empty property toward the bottom.

    I confirmed that SharePoint saved the item and all of its data, and it does indeed redirect me to the thank you page.

    Using SP /SPD 2010.

    1. Hi,
      This is a solution for those with access to edit the form in SPD. If the user do not have access to SPD it is not possible to use this method.

      Alexander

  9. Hey SW,
    I’m trying to do exactly what you describe — edit the RedirectURL property of my submit button. I created a custom newForm.aspx for a list in SharePoint Designer 2007, and removed the default OK button because it wasn’t respecting the RedirectURL property. I added a new submit button to the form, but the RedirectURL is no longer a property of the tag. What am I doing wrong?

    My goal is to have the form return to itself when submitted — because my end users will be entering data quite often and I can save them some clicks by having the newForm.aspx continue to redirect to itself.

    1. the most common error is the src reference. Recheck you are linked to a local copy of the sessvars.js file. If you are sure you are place an alert like this:
      [sourcecode]
      alert(typeof(sessvars));

      what does the alert return?

  10. Alexander,
    Once again, thanks for a great add to the SharePoint Community.

    I am running this in WSS 3.0 and I ran into a small issue with the spUserId variable. It seems it is only available in MOSS.

    I had to utilize SPServices in order to make it work for me. Here is the code in case it helps anyone else.

    Thanks again!
    Mark

    ———————————–
    NEW Form CEWP
    ———————————–

    var userId = sessvars.userId;
    var targetUrl = sessvars.targetUrl;
    var listBaseUrl = sessvars.listBaseUrl;
    var listGuid = sessvars.listGuid;

    if(targetUrl!=undefined && listGuid!=undefined){
    // Query to find the newest item added by current user

    //Grabs the most recent
    var itemId = $().SPServices.SPGetLastItemId({
    listName: “ListDisplayName”
    });

    sessvars.$.clearMem();
    // Redirects the user to the correct item and opens it in EditForm
    window.location.href = targetUrl + “?RequestID=” + itemId;
    }

    ———————————–
    This is the ViewAllItems CEWP
    ———————————–

    function PreSaveAction(){

    // Path of the list to redirect to – current list
    sessvars.targetUrl = ‘http://thesharepointguys.com/mysite/eOOS/html/site/Custom/Pages/ViewRoadmap.aspx’;
    // The BaseUrl of the site or subsite you are located
    sessvars.listBaseUrl = L_Menu_BaseUrl; // SharePoint provides this
    // List Guid of the list to redirect to
    sessvars.listGuid = ‘{F4EC0A9C-5DD5-4426-920B-3817ABFC19F0}’;
    return true;
    }

    $(“input[id$=’SaveItem’]”).val(‘Submit’);

  11. Alexander,

    I was able to have the redirect from NewForm to DispForm work great but now need to redirect from the EditForm to DispForm, keeping the ID, instead of searching for the latest ID. Any help would be greatly appreciated.

    Thanks!

    1. I’m asking this because when I clicked on the ok button after putting the CEWP part with the javascript code in with the absolute url I get an error on page on the status bar. Any idea why that is happening?

  12. Hi Alex, I’ve actually figure out that absolute path works too. But now I’m facing with this problem:

    So how I want it to work is that the user uploads the document in a document library on the main site, then they would be directed to this list in a subsite to type in the information about the document in the list here. And after they entered the information about the document, I want to direct them back to the page where the document library in the main site. How do I dynamically tell the javascript in the subsite to do what I want it to do?

    1. Hi,
      This is all about using the “Source” parameter in the URL.
      If you enter a NewForm with this URL:
      ..Lists/Mylist/NewForm.aspx?Source=/MySite/MyDocLib
      you will be redirected to “/MySite/MyDocLib” when submitting the NewForm.

      Alexander

    2. Hi,

      So there is no way to put some line of code to let the script figure out how to direct the user back to the page right before newForm.aspx? Is there some way to store the cookie or session state of the url of where the user was before newForm.aspx? Is there any other resource I could check out? Thank you so much for the prompt reply, this post has saved me so much time 🙂

    3. Hi,
      You do not need any script. Just include the Source parameter in the URL you are redirecting to and SharePoint will do it for you.

      Alexander

    4. Hi,

      Sorry I’m not quite sure what you meant (I’m pretty new to sharepoint) so can you give me a more detailed direction if I provide more information? Here is the situation I’m facing:

      So users enters goes to different document libraries, say, there are two document libraries at these urls, http://www.mysite.com/doclibA and http://www.mysite.com/doclibB. I was able to use the javascript to bring them to the url that will fill out a form (the newForm.aspx page) in sharepoint list in this url http://www.mysite.com/splist. After they enter the informations in the form I want them to bring back to the document library they were in (so users who enter info in doclibA will be directed back to doclibA after they enters info in newForm.aspx and the same with users in doclibB). How would you achieve that? So you’re saying not to use script, then what would you use?

      Thank you much in advance, you’ve been of great help with everything!

    5. Like this:

      function PreSaveAction(){
        sessvars.targetUrl = '/Lists/MyList/NewForm.aspx?Source=/doclibA';
      return true;
      }
      

      Edit: Didn’t refresh the page…

  13. Hi Alex,

    Now it’s getting a little more complicated because, the users can create folders in the document library, so they will have to be returned to the document library within the folder that they are in. I know that no matter how deep of folders you are in the document library, they will always be going to the same newForm.aspx, but how do I return them to the exact folder they are in before they get brought to the newForm.aspx page? I heard you can get the currentURL and do something with querystring to trim out the parts that you want, but since I’m so new to javascript is there anyway you can help me out? Thanks!

    1. Ok so here is the more specific details.

      I need to get the just the RootFolder=%2FProjects%2FVA%2FVRMPCM%2FQM%2FGnosis%2FGNOSIS%20Document%2FTest

      out of this url (Test is a folder within docLibA):

      http://www.mysite.com/doclibA/…/NewForm.aspx?Mode=Upload&CheckInComment=&ID=59&RootFolder=%2FProjects%2FVA%2FVRMPCM%2FQM%2FGnosis%2FGNOSIS%20Document%2FTest&ContentTypeId=0x010100882464728C3E614A9DB4F3C57A0431C4&Source=….

      I heard you can use querystring (or is there something else) to get the part after RootFolder so it stops before &ContentTypeId (since I only want it up till the test folder)

      Any idea?

    2. Hi,
      Use this to get the rootFolder:

      var rf = GetUrlKeyValue('RootFolder');
      

      Then you reconstruct the rootFolder parameter in the “redirect URL” like this:

      sessvars.targetUrl = "/Lists/MyList/NewForm.aspx?Source=/doclibA?RootFolder="+rf;
      

      Alexander

    3. Hi,

      Thanks Alex! I found a different solution to this but both ways works!!

      Ok, I promise this will be the last one, a minor issue but nonetheless one that needs to be resolved.

      So in the document library, it will call the EditForm.aspx page when one of the following event occurs:

      1. After you upload the document
      2. If you click on edit properties for a particular document

      For upload document, I definitely want to bring it to the NewForm.aspx page for the list so user can enter the info concerning the document in the list. I don’t want to direct the user to NewForm.aspx when the user clicks to edit properties though (i.e. to edit title of the document in the document library), is there a way to set a conditional statement to do that with javascript?

      I tried to see if I can do something in SPD to set the form that upload document would bring up as something different than when a user clicks on edit properties, but it looks like both are set to use the same form…

  14. Hi,
    Put this in EditForm.aspx:

    var isUpload = (GetUrlKeyValue('Mode')==='Upload')?true:false;
    
    if(isUpload){
       // Do the redirect stuff here
    }
    

    Alexander

    1. Hi Alex,

      You.are.the.best!!!!!

      I’m so thankful for all of your help, you should deserve a metal for “best responder to questions” 😛

      I’ll let you know if anything else pops up, otherwise, have a great day!

      Sincerely,
      Peter

  15. Hi Alex,

    There is actually a change in the requirement so now I only want to send them to the NewForm.aspx page for the list from the document library if a checkbox (say, a checkbox for submit to list) is checked. Is there a way to modify the javascript so that it can check to see if the checkbox is checked on that EditForm.aspx list (the one with the javascript) and if it is checked, then it would direct the user to the NewForm.aspx page? Thanks in advance!

    1. Hi,
      Something like this:

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      function PreSaveAction(){
      	var isChecked = $(fields['PutTheFieldInternalNameHere']).find('checkbox').is(':checked');
      	if(isChecked){
      		// Do the redirect stuff here
      	}
      }
      
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);	
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			$(res[fin]).attr('FieldDispName',disp);
      			$(res[fin]).attr('FieldType',type);
      		}		
      	});
      	return res;
      }
      
      </script>
      

      Change the text “PutTheFieldInternalNameHere” with the correct FieldInternalName. Learn how to find it here

      Alexander

  16. Hi Alex, thanks for the help. Now I have another situation that perhaps you can examine as to why it is not working. Here is my script for adding a new ECB menu item:

    function Custom_AddDocLibMenuItems(m, ctx)

    {
    var rf = GetUrlKeyValue(‘RootFolder’);

    var strDisplayText = “Go to Url”;

    var strImagePath = “”;

    var strAction = ‘window.navigate(“/xxx/xxx//NewForm.aspx?Source=” + rf)’

    // Add our new menu item
    CAMOpt(m, strDisplayText, strAction, strImagePath);
    // add a separator to the menu
    CAMSep(m);
    // false means that the standard menu items should also be rendered
    return false;
    }

    I want to direct the user to the url specified in window.navigate command, but for some reason when I click on the newly added item in the ECB menu, nothing happens (status bar just says ‘done’). When I take out the +rf in the var strAction = ‘window.navigate(“/xxx/xxx//NewForm.aspx?Source=” + rf)’ , the item will work and I will be directed to the url /xxx/xxx//NewForm.aspx?Source=”. So something is wrong with the variable rf part to get the value of RootFolder for redirection purpose, but I don’t know why. I still want to be able to direct user back to exactly where they are in the document library after they enter info in NewForm.aspx page, so that’s why I need the variable rf that you help me figure out. Is this within the scope of your knowledge?

  17. hi Alex, I’ve got a new question for you:

    I want to be able to pass the document url of a specific document when I click on an item in its ECB. More specifically, I’ve created a javascript that redirects the user to the EditForm.aspx page, but don’t know how to pass on the document url of the ECB that I click on. Do you happen to know how to do that?

    1. Hi,
      Do you mean the URL of the document you are viewing the editform of?

      Not quite sure if this is the answer, but you have the name of the document on the page in the “Name field”, and you have the URL in the address in your browser.

      These two can be pieced together and will give you the URL.

      Alexnader

  18. 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! 🙂

  19. I put both pieces, but whenever I add the part to NewPages.aspx the OK button which we have labelled Submit will not do anything. As soon as I remove the CEWP it allows us to save.

    Any idea’s?

Leave a Reply