Tuesday, March 12, 2013

Making the browser behave when saving new documents

One issue I had encountered early on in my current project was that the document would create a duplicate copy when the user pushed F9 to refresh the page.   This happened whether I used a partial refresh or a full refresh.   I spent a lot of time trying different things until I found a very helpful blog post by Tommy Valand:  http://dontpanic82.blogspot.com/2010/06/xpages-avoid-saving-duplicate-documents.html

Basically this redirects back to the current document, causing the refresh to do nothing but refresh the current document.   I have found this very useful.  I am going to include this function whenever I do a document.save() in SSJS.

To implement, but the code below in an SSJS code library.   Then call it like this:  redirectToCurrentDocument( false, "Invoices" )

I had to make two changes to Tommy's code to get it to work how I needed it.   

  • First I had to use .getNoteID() instead of .getUniversalID().  I was getting run time errors and this seemed to fix them, why I don't know.
  • Second, I added code to take the user back to the tab they were working on.  Without the tab parameter and query string it would always take the user back to the first tab.  

Here is the code:  (Again, credit for this belongs to Tommy Valand)

function redirectToCurrentDocument( switchMode:boolean, tab){
 try {
   if( typeof currentDocument === 'undefined' || viewScope.stopRedirect ){ return; }
   // Gets the name of the XPage. E.g. /Person.xsp
   var page = view.getPageName();
   // Finds extra parameters, strips away XPages parameters/trims leading &
   var parameters = context.getUrl().getQueryString().substring(1);
   var extraParameters = parameters.replace( 
    /([&\?^]*_[a-z0-9=]+[&]{0,1})|(tab=\w{0,}[\&]{0,1})|(action=\w{4}Document[\&]{0,1})|(documentId=[\w]{32}[\&]{0,1})/ig, '').replace( /\&$/, '' );
   // Gets the unid of the current document
    var unid = document1.getDocument().getNoteID();  //changed to use NoteID since it gave runtime errors
   // Sets/changes the action according according to the mode the document is in
   var isEditable = currentDocument.isEditable();
   if( switchMode ){ isEditable = !isEditable; } // false -> true / true -> false
   var action = ( isEditable ) ? 'editDocument' : 'openDocument';
   // Open the current document via a get request
   var redirectUrl = page + '?documentId=' + unid + '&action=' + action;
   if( extraParameters ){ redirectUrl += '&' + extraParameters; }
    redirectUrl += '&tab=' + tab
   context.redirectToPage( redirectUrl );
 } catch(e){ /* Exception logging */ }

No comments:

Post a Comment