Conditional Save on a Link in a SharePoint Form

Sometimes in a SharePoint form, you might want to include a link which takes the user off to do something else. Maybe it’s to look at another list or some other page; it doesn’t really matter. If you’ve got a nice, fancy customized form using a DVWP, you can make that link a little smarter by adding the sort of “Are you sure?” type of logic you’re used to in many other places.

I have a very old post entitled Parameter-Driven Javascript in XSL that shows how you can build up a Form Action – what happens when you click a form button – variably. Well, you can do the same thing with a plain old text link.

In this example, there’s a link on a multiple item form to take the user to another page to do some other tasks. (It’s a really cool list-driven, spreadsheet-like solution I’m building for a client. I’m sure I’ll post more about it later.)

Here’s the XSL for the link. I’ve created a template to generate the link because I ‘m using the code in several places in the XSL. I’ve defined the xsl:variables $SalaryLink and $SalaryLinkText outside the template (at the top of the XSL) based on the values of some Query String parameters, so they already have values and are available.

<xsl:template name="SalaryLink">
  <a class="clientx-budget-salary-link" href="#">
    <xsl:attribute name="onclick">
      var save = confirm("Do you want to save your changes?");
      if(save) {
        <xsl:value-of select="ddwrt:GenFireServerEvent(concat('__commit;__redirect={', $SalaryLink, '};'))"/>
      } else {
        <xsl:value-of select="ddwrt:GenFireServerEvent(concat('__redirect={', $SalaryLink, '};'))"/>
    <xsl:value-of select="$SalaryLinkText"/>

Here’s what’s going on:

  • Line 2: I start to build up the text link (anchor tag) 
  • Line 3: I begin to create the onclick attribute for the link
  • Line 4: Unsing the JavaScript confirm function, I ask the user if she wants to save her changes
  • Line 5-7: If the user wants to save her changes, I call the JavaScript function negateEntries stored elsewhere to do some preprocessing, then build up the GenFireServerEvent (Form Action) so that it will commit the changes and then redirect to the URL in $SalaryLink.
  • Line 9: If the user doesn’t want to save her changes, then I build the GenFireServerEvent so that it only does the redirect to $SalaryLink (no preprocessing or commit)
  • Line 12: Here I show the text I want the user to see for the link, which is stored in $SalaryLinkText

This is all pretty simple, but it gives the form a bit more intelligence than it would have otherwise. If there was no conditional script behind the text link, then when the user clicked it, she would lose her changes every time, even if the click was an accident.

Have a thought or opinion?