dominoGuru.com
Your Development & Design Resource
Appending and Prepending Field Values in XPages via SSJS
06/01/2011 12:55 PM by Chris Toohey
Sometimes you just gotta add a new value to a field... and sometimes you need to control the order in which the new value is added to said field. In this simple article, you will see how amazingly simple it is to add a new value to a field in an NotesXspDocument!
The trick of this is to think of a multi-value NotesItem as an array of
values. Or more accurately, an Array
.
The SSJS getItemValue
returns an array of values... just like
the LotusScript getItemValue
. But the beauty of SSJS is that you
can use the JavaScript Array
object to easily append or prepend
new values.
var newArr = new Array(thisdoc.getItemValue("foo"));
This SSJS will create a new Array
object variable named
newArr
that will either contain all of the current values from the
foo NotesItem on the NotesXspDocument.
Now that we have our newArr
, we'll use the push
and unshift
JavaScript Array methods to append and prepend a new
value!
newArr.push("blah");
- or -
newArr.unshift("blah");
Again, push
will append where unshift
will prepend
blah to the newArr
JavaScript Array object.
Let's take this a step further and create a simple SSJS function:
- function addToList(thisdoc:NotesXspDocument, fieldname:string, newVal:string, atype:string) {
- var
newArr = new Array(thisdoc.getItemValue(fieldname));
- switch
(atype) {
-
- case
'append':
- newArr.push(newVal);
- break
- case
'prepend':
- newArr.unshift(newVal);
- break
- }
- thisdoc.replaceItemValue(fieldname, newArr);
- return
true;
- }
Now, we can add a new value to a NotesXspDocument NotesItem simply by using the following SSJS function:
addToList(document, "foo", "blah", "append")
Simple yet effective, hopefully this gives you some inspiration on the capabilities of NotesData manipulation with SSJS once you realize just how functional SSJS [and JavaScript objects] can be!