Redirect on NewForm and EditForm another method

This is another method for redirecting a user to a custom page on “OK” and another page on “Cancel”.

I have described two methods in this previous article. This method is a god replacement for the “simple redirect” described in the previous article.

As always we start 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 sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

Add a CEWP below your list-form in NewForm or EditForm, and add this code:
[javascript]
<script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Where to go when cancel is clicked
goToWhenCanceled = ‘/test/English/YouCanceled.aspx’;

// Edit the redirect on the cancel-button’s
$(‘.ms-ButtonHeightWidth[id$="GoBack"]’).each(function(){
$(this).click(function(){
STSNavigate(goToWhenCanceled);
})
});

// Edit the form-action attribute to add the source=yourCustomRedirectPage
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);
}

/*
// Use this for adding a "static" redirect when the user submits the form
$(document).ready(function(){
var goToWhenSubmitted = ‘/test/English/ThankYou.aspx’;
setOnSubmitRedir(goToWhenSubmitted);
});
*/

// Use this function to add a dynamic URL for the OnSubmit-redirect. This function is automatically executed before save item.
function PreSaveAction(){
// Pass a dynamic redirect URL to the function by setting it here,
// for example based on certain selections made in the form fields like this:
var mySelectVal = $(fields[‘MySelect’]).find(‘:radio:checked’).next().text();
if(mySelectVal==’Option one’){
var dynamicRedirect = ‘/test/English/YouSelectedOptionOne.aspx’;
}else if(mySelectVal==’Option two’){
var dynamicRedirect = ‘/test/English/YouSelectedOptionTwo.aspx’;
}

// Call the function and set the redirect URL in the form-action attribute
setOnSubmitRedir(dynamicRedirect);

// This function must return true for the save item to happen
return true;
}

function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf(‘FieldInternalName="’)<0) return;
var start = $(this).html().indexOf(‘FieldInternalName="’)+19;
var stopp = $(this).html().indexOf(‘FieldType="’)-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>
[/javascript]

This script is by default setup with a “dynamic” redirect for “OK” based on the selection made in a “Choice-field” of type “Radio Buttons” with the options “Option one” and “Option two”.

The “OK” redirect can be set to a “static” value if you comment out the function “PreSaveAction()” and uncomment the “$(document).ready(…” function.

The cancel-redirect is set in the top pf the script in the variable “goToWhenCanceled”. The script modifies the “click” attribute of both cancel-buttons and adds this redirect.

Ask if something is unclear

Regards
Alexander

31 thoughts on “Redirect on NewForm and EditForm another method”

  1. hye,

    I have download the jquery using SmartTools J Query loader.
    I have change the script path to my folder ie: /js/jquery.js
    I add the CEWP to my newForm.aspx of one of my list.

    but I still can not get the result I wanted.

    How do I know my .js is working or my modified script has an error?

    thank you in advanced

    1. Hi,
      Try to add this alert to your code:

      alert($);
      

      It will confirm that the jQuery library is loaded by alerting this text:

      function (E, F) {
          return new (o.fn.init)(E, F);
      }
      

      Alexander

  2. Is there a way to automatically make the edit page refresh? The problem I am having is the page loads before the workflows can finish. Normally if they refresh the page once the workflow has enough time to finish. All the Java script I have found puts the refresh on a cycle or a loop which will not work in this case.

    1. I have thought about this scenario and actually have this article half ready written already. I can not promise a publish date, but possibly during this weekend.

      Alexander

  3. Hi Alexander: I have been trying for 8 hours now to get this to work, but can’t. What I’ve noticed (by using alert messages) is that most of the variables are indeed set after adding a new item and transitioning back to the default list page. But the itemID variable is set to “Undefined”, which I’m guess is causing the query to fail when looking for the most recent new item by user, which then causes the whole re-direct to the edit form not to take place.

    Any ideas why this is happening?

  4. Nevermind, operator error 🙂

    It turns out I had the wrong list GUID specified, which causes the code to quit, as intended.

    I learned a good lesson in where to get the list GUID from your other posts, because before I was going into the list settings and grabbing it out of the URL bar, and then having to manually convert the html markup to the appropriate {‘s and -‘s, which obviously I didn’t do correctly. Your tip about viewing the source code of the list page and searching for “listname” gives the exact GUID, already formatted correctly. Had I followed that tip in the first place, I would have saved myself an entire night’s sleep 🙂

    Thanks again for the post–couldn’t have finished this project without it.

    Best regards.

  5. Hmmm…just discovered that this doesn’t work for anonymous users because the _spUserId is undefined…

    Know of any easy work-arounds? This is for a public-facing web site, so I have to be able to use it for anonymous users.

    Thanks in advance.

    1. Hi,
      Still on this article:
      Redirect from NewForm to EditForm or custom page?

      I guess you could query the list for the last added item, but this would not guarantee that you get the right item.

      If you could generate some unique identifier and write to a (hidden) field in the form, you could query the list asking for the item containing your unique value.

      My first thought would be to use the time stamp – it would be down to the millisecond, and therefore would be close to an guaranteed unique value.

      var timestamp = new Date();
      alert(timestamp.getTime());
      

      Ask again if you need help adapting the function.

      Alexander

  6. Great post, just what the doctor ordered. Question… If I use this on an editform (for ID=45 or whatever) can I have the “OK” button take me back to the dispform for ID45 or just take me back 1 page, from wherever it was that I came?

    Thanks again for the post.

  7. After installing the CEWP and code I noticed that I was no longer able to delete the item from the dispform.aspx page.

    If I clicked “Edit” I am able to delete the item on the editform.aspx page. I noticed the dispform.aspx URL ends in ID=XX while the editform.aspx ends in ID=xx&Source=%2FLists%2FCTL%2FMyItems%2Easpx.

    suggestions?

  8. hey Alexander,

    great code, works perfectly with the Save button, but i couldn’t make it work for the Cancel button.

    I am trying to redirect to a custom page, rather than to its original page.

    Can you please give me a sample code that will definitely help me.

    Thanks in Advance…
    alien

    1. Hi,
      Sorry for the late reply.

      The code example above has all the code needed:

      // Where to go when cancel is clicked
      goToWhenCanceled = '/test/English/YouCanceled.aspx';
      
      // Edit the redirect on the cancel-button's
      $('.ms-ButtonHeightWidth[id$="GoBack"]').each(function(){
          $(this).click(function(){
      			STSNavigate(goToWhenCanceled);
      	  })
      });
      

      This code example does not affet the ribbon-buttons in SharePoint 2010.

      Alexander

  9. Hi Alexander,

    Is it possible to Go Back to the previous page. I am navigating to an edit form from a number of different Webpart pages. All I need to do is Navigate from where the user has came from. I can achieve this on the cancel button:-

    // Edit the redirect on the cancel-button’s
    $(‘.ms-ButtonHeightWidth[id$=”GoBack”]’).each(function(){
    $(this).click(function(){
    history.go(-1);
    })
    });

    But how do I achieve the same thing when the user clicks the submit button.

    Thanks

    1. Hi,
      If you have control over the links that point to the EditForm you can use the URL parameter “Source” like this:
      …/YourList/EditForm.aspx?ID=123&Source=/The_Path_You_Want_To_Return_To

      This will take you back to where you came from when you save the list item.

      Alexander

      1. Hi,

        Unfortunanly that solution will not work. The webparts are filtered for specific criteria. I have 3 different web part pages with hyperlinks that will open specific records from the same list.

  10. The code above works great for Cancel button functionality but for Submit button, the action is updated in the form tag but finally when the submit button is clicked, it goes back to list view instead of the custom link provided. By the way I am doing a static redirect in SharePoint 2013 online environment in a list edit form.

    Any help is greatly appreciated.

    Thanks
    Suhas

    1. Hi,
      Unfortunately I don’t have a working solution for redirecting directly from a form that is submitted in SP2013. The best tip I can give is to set up some code in the default list view to do the redirect.

      You might be able to use a cookie to set the redirect in the form, and teh list view code in the list view to pick it up and redirect you.

      Alexander

Leave a Reply