Redirect to Another Page from NewForm.aspx with the New Item’s ID

UPDATE 2009-10-19: I solved this for real in the jQuery Library for SharePoint Web Services function called $().SPServices.SPRedirectWithID.  Feel free to read this post, but this is the solution you’re looking for.

UPDATE 2009-10-01: I’ve posted an update on this idea.  It’s possible to simplify the interstitial page using the Web Services from the jQuery Library for SharePoint Web Services, but I’m still not satisfied: Redirect to Another Page from NewForm.aspx with the New Item’s ID: Redux.

Here’s a good question from prostration in the MSDN SharePoint – Design and Customization forum:

I need to go from the newform page to the editform page of the item I just created. So when I click save I want it to create the item and take me to it’s editform page. How can I do this?

My first answer was bollocks, but I do have a workable approach.

The problem is that the ID for the new item is unknown before the item has been created.  I came up with a scheme about a year ago to deal with this, and some Binging tells me that there aren’t any spiffier ideas out there, at least that I could find.

The trick is to commit the new item and then determine its ID to pass to whatever page you want on the Query String.  I did this by creating an intermediate page which just finds the ID with a DVWP and then redirects to the other page.

So first convert the NewForm.aspx to XSLT.  (I usually just create a new DVWP from scratch so that I can keep the page code clean.)  Then, change the Save button behavior like so:

<input type="button" value="Save" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={GetLastID.aspx?RedirectURL=EditForm.aspx}')}" />

The code for my intermediate page is below.  Note that I’ve constructed it so that you can pass in the redirect page (RedirectURL) so that you can use it to do other things.  All this page does in its DVWP is find the most recent item in the list which was created by the current user and redirect to RedirectURL with the ID on the Query String.

<%@ Page Language="C#" inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<html>

<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>
<form id="form1" runat="server">
<WebPartPages:DataFormWebPart runat="server" IsIncluded="True" FrameType="None" NoDefaultStyle="TRUE" ViewFlag="0" Title="Events" __markuptype="vsattributemarkup" __WebPartId="{020AF483-2135-4D37-B6C7-CD6A6FD6AF5D}" id="g_a8a4d070_e7c0_4105_a113_acff9dea3328" pagesize="1" __AllowXSLTEditing="true" WebPart="true" Height="" Width="">
    <DataSources>
        <SharePoint:SPDataSource runat="server" DataSourceMode="List" UseInternalName="true" selectcommand="<View><Query><Where><Eq><FieldRef Name=&quot;Author&quot;/><Value Type=&quot;Integer&quot;><UserID/></Value></Eq></Where><OrderBy><FieldRef Name=&quot;Created_x0020_Date&quot; Ascending=&quot;FALSE&quot;/></OrderBy></Query></View>" id="dataformwebpart2">
            <SelectParameters>
                <WebPartPages:DataFormParameter Name="ListName" ParameterKey="ListName" PropertyName="ParameterValues" DefaultValue="Assignments"/>
            </SelectParameters>
        </SharePoint:SPDataSource>
    </DataSources>
   
<parameterbindings>
        <ParameterBinding Name="UserID" Location="CAMLVariable" DefaultValue="CurrentUserName"/>
        <ParameterBinding Name="RedirectURL" Location="QueryString(RedirectURL)" DefaultValue=""/>
    </parameterbindings>
    <datafields>@Title,Title;@Start_x0020_Time,Start Time;@End_x0020_Time,End Time;@ZIP_x0020_Code,ZIP Code;@Amount,Amount;@Nominee,Nominee;@ID,ID;@ContentType,Content Type;@Modified,Modified;@Created,Created;@Author,Created By;@Editor,Modified By;@_UIVersionString,Version;@Attachments,Attachments;@File_x0020_Type,File Type;@FileLeafRef,Name (for use in forms);@FileDirRef,Path;@FSObjType,Item Type;@_HasCopyDestinations,Has Copy Destinations;@_CopySource,Copy Source;@ContentTypeId,Content Type ID;@_ModerationStatus,Approval Status;@_UIVersion,UI Version;@Created_x0020_Date,Created;@FileRef,URL Path;</datafields>
    <XSL>
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal">
    <xsl:output method="html" indent="no"/>
    <xsl:param name="UserID">CurrentUserName</xsl:param>
    <xsl:param name="RedirectURL" />
	<xsl:template match="/" xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:SharePoint="Microsoft.SharePoint.WebControls">
        <xsl:call-template name="dvt_1"/>
    </xsl:template>

    <xsl:template name="dvt_1">
        <xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row"/>
        <xsl:for-each select="$Rows">
            <xsl:call-template name="dvt_1.rowview" />
        </xsl:for-each>
    </xsl:template>

    <xsl:template name="dvt_1.rowview">
        <script type="text/javascript">
            document.location.href = &apos;<xsl:value-of select="$RedirectURL" />&apos; +
                &quot;?ID=&quot; + &apos;<xsl:value-of select="@ID" />&apos;;
        </script>   
    </xsl:template>
    </xsl:stylesheet>
</XSL>
</WebPartPages:DataFormWebPart>
</form>
</body>
</html>

Similar Posts

63 Comments

  1. Hi,

    For some reason I cannot get the redirect to work. It says the web page cannot be found.

    If I click on the GetLastID page, I can see that it is returning the correct ID for the last item added, however, the redirect is not working.

    Can you shed any light?

    Im using SP 2010 if that would be causing the issue?

    Cheers,
    Phil

    1. Phillip:

      Are you using the method in this post or SPRedirectWithID from SPServices? If it’s the latter, please post more details, including your code, to the discussions on the SPServices Codeplex site.

      M.

      1. Hi Marc,
        Its the code on this post I am using. It’s obviously something I am doing as others have got the function to work.

        Does the GetLastID page need to be in a specific location perhaps? or of a certain type?
        I have addded it to sitePages as a wiki page, would that be causing an issue?

        Phil

        1. Phil:

          It’s hard to say what might be going on without doing debugging in your environment. Items are added to list asynchronously, so it may be that you have a race condition.

          As I note in the red message at the top of the post, I recommend using SPRedirectWithID in SPServices instead. (Please be sure to read the caveats in the docs for 2010.) The solution outlined here worked in one situation, but it’s clunky and could be unreliable.

          M.

  2. Thanks Marc,
    I will have a look at that example. Well, I will on Monday morning (its Friday afternoon after all!!

    Actually, just looking at it, the need for a redirect on the save button on my custom form? Where should I point the redirect to? The EditForm.aspx?

    Cheers,
    Phil

  3. Couple other questions:

    Where abouts to I add the code into the newForm.aspx? Does it matter where?

    Do I need to enable anything else for the code to work?

    Cheers,
    Phil

    1. Phil:

      You need to read the documentation on the SPServices site, and not just what’s on the SPRedirectWithID page. The first doc page is a good place to start.

      If you get stuck, post your questions and the code you are using in the SPServices discussions, not here.

      M.

  4. Hi Marc,thank you somuch for sharing these things.,,i have one question help me on this.

    I am using “Intermediate page” method to get latest ID created by user and its working fine but ….

    if the user is not entering data in new form and cliking save button it should redirect it to edit form with the item what the current user created before… will this functionality will work..please give me your valuable suggestions to solve this issue.thank you..

    1. Surya:

      You’ll need to adapt the code to make that work. If you’re uisng the intermediate page method here, you’ll need to add some sort of test to figure out how to handle the situation you describe, which isn’t something I ever considered.

      M.

  5. Marc, thanks for quick reply.
    Do we have another option other than intermidate page to make this functionality to work..can we use web services? any suggestions? thank u/…

    1. surya:

      The red text right at the top of the post points you to what I consider my “real” implementation of this idea in SPServices on Codeplex. You can always adapt that code to your needs.

      M.

  6. Hello Marc,
    I need Same functionallity as u mention above. but i want last itemID.
    Above u mention we have to create an GetLastID.aspx. what type of page it is.. its an webpart page or wiki page created by browser in site collection or wiki page created by SharePoint Desginer. and in which page i have to add/paste ur code.
    And my requirement was i have to add data into list and i redirect to other list newform.aspx.
    How can achive this..

    1. Raghu:

      You can’t display the ID in the NewForm because it doesn’t exist until you save the item. That’s the point of this post and the SPServices function.

      M.

  7. I’m trying to find a solution to redirect to a different URL in a DVWP submit form based on a value that is selected. For example if the user selects a drop down with Yes, redirect to http://www.google.com and if not, just continue on with it’s regular submit action. I found the __redirect in the form button to use, but not sure how to pass it a variable instead. It seems less complicated than what you are doing in this article but I’m stuck!

  8. Thanks,

    This solution worked for me where others didn’t.

    As a SharePoint beginning, it seems odd that there isn’t an OOTB method to do this.

  9. Does anyone have a solution to redirect to another page using a content editor webpart? We are not permitted to use Designer and cannot create DVWP’s.

Leave a Reply

Your email address will not be published. Required fields are marked *

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