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 Marc, it was actually the dispform page that I wanted to show. I’m creating some kind of wizard, so I just want the user to see the item he just created and from there he can go to the newform page of another list passing some values.

    I tried your code but it’s always taking me to the ediform of the first item in the list, I’m pretty new at this so bear with me. I created an apsx file(GetLastID) and inserted a dataview with the fields from the same list where I create the item as a single item view, then I added the parameters UserID and RedirectUrl and then the javascript, what am I doing wrong?

    1. Note that you want to grab the most recent one item by creation date, so you need that sort and filter in place as I have in my CAML above. To change to DispForm.aspx, just change the redirect page on the button’s onclick event.

      M.

  2. Oh god I don’t know how I missed this, works like a charm.

    I actually changed my mind and made it go straight to the newform page of the second list where I need my user to fill out a form, your solution is key here as I need to pass some of the values from the last item created in the first list via query string, it’s bloody brilliant really, thanks a lot.

  3. Thanks Marc for this wunderful solution !

    I wanted to open the default.aspx after a save at EditForm.aspx. Here is my solution.

    document.location.href = ''
    + "?ID=" + ' '
    + "&SOURCE=" + '../../default.aspx';

  4. You can use web service for item adding then get the newly ID from the response XML. Now, when you have the item ID, you can do whatever you want with it.

    With this method, you don’t have to care about more than one user add list items at the same time. Anyway, you have to pay your time for a complex NewForm.

  5. True, Dathq, but this method works entirely in the context of DVWPs, so it is undoubtedly preferable to some developers. Always more than one way to skin a cat!

    M.

  6. Hi

    I am using sharepoint designer. I have copied your code for the Redirect.aspx page, but I get an error that webpart cannot be displayed properly. I am not sure which values are specific to your list and which I need to replace with fields for my list. Would really appreciate it if you could let me know which bits I need to substitute with values specific to my list.

    Many Thanks

    Andrew

    1. Andrew:

      In the SelectParameters section you need to replace “Assignments” with the name of your list. Note that I’m using ListName here rather than the default ListID. I prefer this since it makes the code more understandable (and portable), but if you rename your list you’ll need to change the code as well.

      M.

      1. Thanks for your reply Marc. Do I need to worry about the “Datafields” section as the fields in my list are different to yours. Also the CAML query uses a field “Author”, is that a standard field in a sharepoint list? Thanks!

  7. Andrew:

    When you edit the DVWP in SharePoint Designer, it ought to fix up the DataFields for you. As for the Author, yes this is the standard “Created By” column. FYI, here are the standard aliases and their columns (not totally obvious):
    Created By –> @Author
    Modified By –> @Editor

    M.

  8. Hello Marc,

    I was happy to find this blog and this will actually work. I am building a Job tracking site for my company. The DispForm has a web part at the top with the job info and a web part at the bottom with the items on that job. My goal is, when I create a new job it goes back to that newly created job DispForm so I can enter new items on that job.

    On my GetLastID.aspx page, I’m getting an error:
    “This Web Part Does not have a valid XSLT stylesheet: Error: The character ‘<' cannot be used in an attribute value. http://www.w3.org/2001/XMLSchema&quot; 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”>

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.