Bryan Schmiedeler
Bryan Schmiedeler

Reputation: 3127

Xpages: Getting a sessionScope Array in CSJS

I am working on an application that uses Xpages and KendoUI. In one particular page I have a tool bar with a button with "Add Record". The button opens a window and the user will select one from a piece of data and that will create a new record.

The list of data are employee names and I must compute them. I do so in a sessionScope [could be viewScope] array in the beforePageLoad, like so:

<xp:this.beforePageLoad>
<![CDATA[#{javascript:viewScope.myArray = []; 
viewScope.myArray.push("1st Val");
viewScope.myArray.push("2nd Val"); 
viewScope.myArray.push("3rd Val");}]]>
</xp:this.beforePageLoad>

The dropdown needs data in the following format:

  var data = [
                { text: "Black", value: "1" },
                { text: "Orange", value: "2" },
                { text: "Grey", value: "3" }
                ];

For the life of me I cannot get the data into that format. It looks like a javascript object to me.

How do I get the array in the viewScope into the format I need?

var o = {};
o = "#{javascript:viewScope.get('myArray');";

Upvotes: 0

Views: 942

Answers (2)

xpages-noob
xpages-noob

Reputation: 1579

All SSJS Array objects added to any of the scopes are converted to java.util.Vector (how to update a value in array scoped variable?) which can not be stringified with the standard toJson function. This can be circumvented by creating an intermediate object to store the array in:

viewScope.myData={myArray:[]};
viewScope.myData.myArray.push( { text : 'Mark' , value : '1' } );
viewScope.myData.myArray.push( { text : 'Bryan' , value : '2' } );

Also, I doubt your line of code returns the right data without any explicit JSON conversion. I would write it as:

var myArray = #{javascript:return toJson(viewScope.myData.myArray);};

Upvotes: 3

Renaud Thi&#233;vent
Renaud Thi&#233;vent

Reputation: 211

When you set your client side js variable called o it's a string because the value is between "".

So just remove the double quotes and you'll get it as object.

o=#{javascript:viewScope.get('myArray')};

But be aware you might get an js client side error if the viewscope value is not a valid client side JS object !

You can also set the variable o to a string as you did in your example and use the eval clientside method to evaluate the string as an object.

o=eval("#{javascript:viewScope.get('myArray')}");

P.S. In your example there is a } missing is at the end of your SSJS code when you set your "o" variable.. ;-)

Upvotes: 1

Related Questions