Wednesday, May 23, 2012

Popup Window After Event Receiver Fires

So here's a low tech approach to firing off a popup window after an event receiver fires. This approach makes the following assumptions:
  • Event occurs at list item level
  • Event Receiver cannot interrupt save process
  • Popup window loads after event receiver fires
  • Parent window loads list after save
So, what you need are the following objects:
  • Event receiver that inherits SPItemEventReceiver
  • Redirect Page
  • Popup page

Your first step is to create a new event receiver object. The event receiver will override the ItemAdded or ItemUpdated events. Bear in mind that these events are, by default, asynchronous events. Edit the elements.xml file for the event receiver to include a Synchronization node that specifies a synchronous action. Your XML should resemble the following:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListTemplateId="100">
      <Receiver>
        <Name>MyProject_EventItemAdded</Name>
        <Type>ItemAdded</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MyProject_PopupEvent.MyProject_Event</Class>
        <SequenceNumber>10000</SequenceNumber>
        <Synchronization>Synchronous</Synchronization>
      </Receiver>
  </Receivers>
</Elements>

Next step is to include a constructor in the EventReceiver that initializes a variable to the Current HttpContext such as:

if (current == null)
                current = System.Web.HttpContext.Current;

Step 3 includes modifying the overridden ItemAdded or ItemUpdated events that perform a simple redirect call to the redirect page such as:

current.Response.Redirect({redirectUrlString});

Step 4: Your redirect page can be a simple page with inline code that captures any querystring values or anything that you want to pass on to the popup window. Otherwise, the redirect page will hold javascript code that generates the popup window such as:

 <script type='text/javascript'>
 <!-- 
     
     window.open("<%=_PopupURL %>", "PopupWindow", "location=0,status=0,scrollbars=0, width=550,height=650");

     if (window.location != window.parent.location) {
         window.frameElement.commitPopup();
     }
     else if (window.frameElement != null) {
        window.frameElement.waitDialog.close();
     }
     else {
         window.location = "<%=_SourceURL %>";
     }

// -->
</script>

Couple of things to note:
1. This javascript code accounts for whether the redirect page was called from a dialog page or a full page.
2. The _PopupURL and _SourceURL variables are derived from inline code on the redirect page
3. The redirect page either closes itself if it came from a dialog page or redirects to another page if it was called from a full page.

Happy coding.