I am modifiyng exisiting code which currently does
currentDocument.setValue("field", requestScope.variable);
This works well, but I now need to make it a little more dynamic so, I have the requestScope.variable
stored as a string. I know I can do:
requestScope["variable"]
but this relies on me knowing which scope it is in. Given that the string could be requestScope.variable
or even applicationScope.variable
I think this route is closed to me.
I had also thought of splitting the string based on the . but think that there must be a more straightforward option.
How can I go about doing this?
Use ${javascript:'requestScope.variable'}
to get the value of the scope variable which is defined as a string.
Your example would be
currentDocument.setValue("field", ${javascript:'requestScope.variable'});
${javascript:...}
works here a preprocessor and inserts the result into the code.
Here is a complete example:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view
xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.beforePageLoad><![CDATA[#{javascript:
sessionScope.test = "this is the value of sessionScope.test";
viewScope.other = "this is the value of viewScope.other";
requestScope.myScopeVariable = "viewScope.other";
}]]></xp:this.beforePageLoad>
<xp:text
escape="true"
id="computedField1"
value="#{javascript:
var valueFromSessionScope = ${javascript: 'sessionScope.test'};
var valueFromViewScope = ${javascript: requestScope.myScopeVariable};
valueFromSessionScope + ' ... ' + valueFromViewScope;
}">
</xp:text>
</xp:view>
It shows as result:
this is the value of sessionScope.test ... this is the value of viewScope.other
Hmm, I've never seen requestScope["variable"] though that makes sense. I typically use something like requestScope.get("variable").
Also my scoped variables always get a prefix to indicate the scope. rsVariable, ssVariable, vsVariable, asVariable. If you did something like that then you could maybe inspect your variable name and pick the right scope. BUT the reason I did that is I had some kind of scope collision once. I forget the circumstances. But remember, XPages does a lot to "resolve the variable". I'm not fully sure how this "variableRolver" as we call it works in SSJS. But similar to how I had that problem once, there's likely someway to get a variable without knowing the scope.
Worse case, as long as your variables have unique names, remember that scoped variables are just Java HashMaps. So you can do something like : viewScope.containsKey("ssMyVariable") so see if it exists in that scope.
Just some quick thoughts.