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:

<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>

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

25 Responses to “Redirect on NewForm and EditForm another method”

  1. Redirect from NewForm to EditForm or custom page « SharePoint JavaScript's Says:

    [...] Redirect from NewForm to EditForm or custom page By Alexander 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. [...]

  2. Links (11/22/2009) « Steve Pietrek – Everything SharePoint Says:

    [...] Redirect on NewForm and EditForm another method [...]

  3. ashiena Says:

    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

    • Alexander Says:

      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

  4. Tweets that mention Redirect on NewForm and EditForm another method « SharePoint JavaScript's -- Topsy.com Says:

    [...] This post was mentioned on Twitter by SharePoint, SharePoint. SharePoint said: Redirect on NewForm and EditForm another method SharePoint JavaScript http://bit.ly/5HywNG [...]

  5. Scott Muldowney Says:

    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.

  6. tony camacho Says:

    no sarcasm I understand script but how do i implement in edit or new page? I assume i unghost and where do I use in that in ghosted page?

    T

    • Alexander Says:

      Hi,
      As written in the article:
      Add a CEWP below your list-form in NewForm or EditForm…

      Click on the link on CEWP to read how you do this.

      Alexander

  7. Jim Parker Says:

    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?

    • Alexander Says:

      Hi,
      I guess this question is about this article:
      Redirect from NewForm to EditForm or custom page.

      Double check the List GUID, or use the lists displayname. Also try to put in an alert between line 15 and 16 like this:
      alert(res.count);
      If this returns “-1″ there is something wrong with the query.

      Try this and get back to me if you do not get it.

      Alexander

  8. Jim Parker Says:

    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.

  9. Jim Parker Says:

    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.

    • Alexander Says:

      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

  10. Siby Says:

    Hi – is it possible to change text of OK button to “Submit”?

  11. Siby Says:

    Thanks…very useful!!

  12. Dave S Says:

    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.

  13. Dave S Says:

    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?

  14. Chris Says:

    Is it possible to use this on a custom form? I can’t seem to figure it out?

    • Chris Says:

      Figured it out. Love the JQuery site.

      var mySelectVal = $(‘input:radio[name=inputname]:checked’).val();

  15. alienrock Says:

    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

    • Alexander Bautz Says:

      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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 435 other followers