How to check if variable exists in java script

Hello,

I want to check if a process variable (e.g. cam-variable: inputOrderName) already exists when i start a new user task-form in an embedded camunda Form.

I tryed in the following function camform.on("form-loaded:)

  1. Try: if (camForm.variableManager.fetchVariable('inputOrderName') != null){...};
  2. Try: if (camForm.variableManager.variableValue('inputOrderName') != null){... };

Problem with 1. try, with that expression it also somehow fetchs the variable if I want to set at the end of the form camForm.variableManager.createVariable({name: 'inputOrderName',type: 'String', value: camForm.formElement.find('#inputOrderName')[0].value,}); an error-message appears that the variable already does exist (Even though it does not).

Any solutions how to check if there is a variable with the name “inputOrderName”?

camForm.on('form-loaded', function() {
     variableManager.fetchVariable('inputOrderName');
});

camForm.on('variables-fetched', function() {
     if(variableManager.variableValue('inputOrderName')) {
        // does not exist
     }
});

A tend to look at the source from time to time to grasp the behavior of the variableManager:

hello nvanbelle,

The problem with your method is that, ones you have fetcht a variable, you can not use the createVariable with the same name any more. Because it says that the variable already exists.

My current solution not very sexy but works

var x = "0";    
camForm.on('form-loaded', function() {
if (typeof inputOrderName !== 'undefined') { 
}else{camForm.variableManager.fetchVariable('inputOrderName');
   x="1"; });

camForm.on('variables-fetched', function() {
   if(x== "1") {
        $scope.inputOrderName = camForm.variableManager.variableValue('inputOrderName');
     }
});

if the variable exists already you have 2 options

  1. delete the variable from the manager and re-create:
    camForm.variableManager.destroyVariable('inputOrderName'); camForm.variableManager.createVariable({name:'inputOrderName',type:'String',value:'myNewValue'});
  2. overwrite the variable value
    camForm.variableManager.variableValue('inputOrderName', 'myNewValue');

If you look at the source code of the variableManager you see that an entry is made when you invoke fetchVariable but only the name will be filled, not the value. I’m not a fan of this behaviour but it’s just the way it works.

2 Likes

Hi nvanbelle

yes, thanks im using the destroy method now.

cheers
Marc

In my case, I solve it the following shape:

if (variableManager.variable(‘myVariable’) != undefined) {
camForm.variableManager.destroyVariable(‘myVariable’);
}

camForm.variableManager.createVariable({
name: ‘myVariable’,
type: ‘String’,
value: ‘myNewValue’,
isDirty: true
});

1 Like