Clientside onLoad events on Xpages

I wanted to set the focus (client side) on an input field in my Xpage. This required:
  • adding a function to the onLoad event
  • referencing the (generated) id of my editable field: in the Xpage the element is named “userName”.

As I found out, there are a couple of ways to add clientside javascript to your Xpage (the dojo.addOnLoad function I’m using defers execution of the code until all HTML is loaded, so it doesn’t matter where you place your code):

  • Add the code directly to the XPage source:
    <script type="text/javascript">
    dojo.addOnLoad( function() {
     alert("added directly in source");
    } );
    </script>
  • Add a Computed Field to your Xpage, set its Content type to “HTML” and enter a value that evaluates to a string, including the <script> tags:
    "<script type="text/javascript">" +
    "dojo.addOnLoad( function() {" +
    " alert("computed field");"
    "} );"
    "</script>"

    The value if the computed field is computed on the server, so if I want to get the generated ID of the Editable field, I have to use the getClientId() function:

    "<script type="text/javascript">" +
    "dojo.addOnLoad( function() {" +
    " alert("The id of the element is: " + getClientId("userName") + "");" +
    "} );" +
    "</script>"
  • Add an “Output script” core control to the Xpage and edit its value. This control is rendered in the browser with <script></script> tags (if “Output script” isn’t available in the menu you have to enable it in the Designer preferences through File – Preferences – Domino Designer – Palette – Core Controls):
    dojo.addOnLoad( function() {
        alert("Output script control");
    } );

    The value of the Output script is passed to the browser as clientside Javascript, but is first evaluated by the server. So if I wanted to reference a clientside document ID, I’d have to use the “#{id:userName}” syntax:

    dojo.addOnLoad( function() {
        var id = "#{id:userName}";
        alert("The id of the element is: " + id);
    } );

Since the first method didn’t allow me to reference the generated ID of the Editable field and the second method required me to escape and wrap everything in quotes I went with the third method. The final code in the Output script element is now:

dojo.addOnLoad( function() {
 var objFocus = dojo.byId("#{id:userName}");
 if (objFocus) {
   if (!objFocus.disabled &amp;&amp; objFocus != "hidden") {
     objFocus.focus();
   }
 }
 } );

To set the focus only if a new document is being edited, I’ve added the following formula to the “rendered” property of the Output script control:

currentDocument.isEditable() &amp;&amp; currentDocument.isNewNote();

XPages “Change document mode” not working (and why)

I just tried to add a “Change Document Mode” action on an XPage to be able to switch between read- and edit mode. The XPage (containing the document) opened fine in read mode, but after clicking the “Edit”  button, nothing happened. At first I thought it was trying to put the wrong data source in edit mode or that it had something to do with using multiple custom controls. A simple test with a new Xpage showed that this wasn’t the case. I then tried other things: changing the view control that showed all documents to open the document directly in edit mode, adding an ?action=editDocument parameter to the URL: all with no success.

Then it occurred to me: is the user allowed to edit the document at all? He wasn’t… Back in the days the Domino server used to tell you “you’re not allowed to perform that operation”, but that doesn’t seem to happen anymore: the document just stays in read mode.

The solution was to show the “edit” button only if the user is actually allowed to edit the document. To do that I wrote a function for the Visible property of the “edit” button that checks if the user is allowed to edit a document and hides it if he isn’t:

  • It first checks the access level to the parent database: editors or higher are allowed to edit, readers or lower are not.
  • If the user is an author it checks a field called docAuthors (which I use to store document authors in): if that field contains the current user’s username or one of its roles the user is allowed to edit.
Here’s the function:
function isAuthor( doc:NotesDocument ) {

    var level = doc.getParentDatabase().getCurrentAccessLevel();
        
    if (level >= 4) {
        return true;        //editor or higher
    } else if (level < 3) {
        return false;        //reader or lower
    } else {    //author
        
        var authors = doc.getItemValue("docAuthors");        //field containing all document authors
        if (authors === null) { return false; }        //no authors field present
        
        var userName = @UserName().toLowerCase();
        var roles = context.getUser().getRoles();  

        for (var i=0; i<authors.length; i++) {
            if (authors[i].substring(0,1) == "[") {        //role
                for (var j=0; j<roles.length; j++) {
                    if (authors[i].toLowerCase() == roles[j].toLowerCase()) {        //on of user's roles is in authors field
                        return true;
                    }
                }
                
            } else if (authors[i].toLowerCase() === userName ) {    //username matches one of the values in the authors field
                return true;
            }
        }
    }  

    return false;
} 

UPDATE 1 Serdar Basegmez came up with a Java version for this function. Since he’s from Turkey it will probably even work for users with a dotless-i in their name 🙂

 @SuppressWarnings("unchecked")
public static boolean isAuthor(Document doc, String authorField) {
               
  try {
    Database db=doc.getParentDatabase();
    Session session=db.getParent();
                       
    int level = db.getCurrentAccessLevel();
                             
    if (level >= 4) {
      return true;        //editor or higher
    } else if (level < 3) {
      return false;        //reader or lower
    } else {    //author
   
      Vector<String> authors=doc.getItemValue(authorField);
 
      if (null==authors || authors.isEmpty()) { return false; }        //no authors field present
                         
      Vector<String> checkList=session.evaluate("@UserNamesList");
                           
      for(int i=0; i<checkList.size(); i++) {
        String checkStr=checkList.get(i);
        checkList.set(i, checkStr.toLowerCase(Locale.ENGLISH));
      }
     
      for (int i=0; i<authors.size(); i++) {
        String checkStr=authors.get(i);
        if(checkList.contains(checkStr.toLowerCase(Locale.ENGLISH))) {
          return true;
        }
      }
    }
  } catch (NotesException e) {
    // Nothing to do
  }
         
  return false;
}

UPDATE 2: Philipp Bauer mentioned that you can also check if the current user is allowed to edit a document with the built-in isDocEditable() function:

import com.ibm.domino.xsp.module.nsf.NotesContext;
import lotus.domino.NotesException;

public static boolean isAuthor(Document doc) throws NotesException {
   NotesContext localNotesContext = NotesContext.getCurrent();
   return localNotesContext.isDocEditable(doc);
}