Category Archives: Redirect user

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

Manipulate upload link in document library

I got this request from JGilmore:

Anyone know how to change the URL of the ‘Upload’ button as well as the links under its dropdown? I would like to have the user directed to a custom upload page with ‘Overwrite existing files’ unchecked by default.

Thanks in advance.


Here is one possible approach

Add this code in a CEWP below the list view to override the default links:
[javascript]
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">

// Manipulate direct click on upload button
$("*[id$=’_UploadMenu’]").parents(‘td:first’).removeAttr(‘onclick’).click(function(){
redirectUpload(false);
});

// Manipulate "Upload Document"
$("*[id$=’_Upload’]").attr(‘onMenuClick’,’redirectUpload(false)’);

// Manipulate "Upload Multiple Documents"
$("*[id$=’_MultipleUpload’]").attr(‘onMenuClick’,’redirectUpload(true)’);

function redirectUpload(multi){
// Set your new upload destination (custom upload page)
// ctx.listName is provided by SharePoint
if(multi){
window.location=’/test/English/MyCustomUploadPage.aspx?List=’+ctx.listName+"&MultipleUpload=1";
}else{
window.location=’/test/English/MyCustomUploadPage.aspx?List=’+ctx.listName;
}
}
</script>

[/javascript]

Change the new upload location in the function “redirectUpload”. Also edit the source of the jQuery script if you prefer to use a local copy.

Ask if anything is unclear.

Alexander

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

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