Only set variable value if it doesn't exist already

Hey there!

I need a way to only set a variable’s value if it doesn’t exist already.
Somethig along the lines:

  1. Check if the variable already exists and has a value
  2. If it exists and has a value, then keep said value
  3. If it doesn’t exist or doesn’t have a value, creates the variable with specified value

I remember previously solving this problem with execution.hasVariable and execution.setVariable but I’m not getting it right this time.

Hi @Neeniih

Are you doing this as part of a script or a java delegate?

In Java you could do this

       if(execution.hasVariable("VarName")){
           return;
       }else {
           execution.setVariable("VarName", "VarValue");
       }

The same kinda thing would work in a script with a change in syntax

1 Like

Hello @Niall !

It’s a .js file attached as a External Resource to a Script Task.

Sounds about right! Lemme try.

1 Like

Error message:

Cannot instantiate process definition e50c7cef-8e63-11ec-919c-0242ac120003: Unable to evaluate script while executing activity 'InitializeCarePathwayHierarchyTask' in the process definition with id 'e50c7cef-8e63-11ec-919c-0242ac120003':org.graalvm.polyglot.PolyglotException: SyntaxError: <eval>:17:4 Invalid return statement\n    return;\n    ^\n<eval>:18:0 Expected eof but found }\n}else {\n^\n

PS: I’m not a dev so the solution might be obvious but I don’t have such knowledge.

Hi @Neeniih
What if you change return; to return true;?

1 Like

Tried if (!execution.hasVariable("someVariable")) execution.setVariable("someVariable", "someValue"); and it worked!

Thanks everyone.

1 Like