Environment Variable and Magic Variable Syntax, Usage, SDK, and Script Examples
Reference Environment Variables and Magic Variables in your Scripts.
Environment Variable Syntax, Usage, SDK, and Examples
ProcessMaker Platform uses two global variables that Scripts can call. Variable usage depends on the programming language that the Script uses. Below is a description of these global variables:
Data: The data variable is a JSON object that contains all Request data to the moment a Script runs.
Config: The config variable is a JSON object that contains any special configuration to be passed to the Script prior to it running. In Script Task elements of a Process model, special configurations are entered into the Script Configuration setting. See Reference a Request Variable from a Script Configuration Setting as to the best practice when configuring Scripts from Script Task elements in a Process model.
Every Script Executor from which a Script runs has the following default Environment Variables from which a Script may get its value. Refer to the tabs below how to get these Environment Variable values for each supported programming language. Below is a description of these default Environment Variables.
Environment Variable
Description
HOST_URL
Domain for the ProcessMaker Platform instance.
API_HOST
ProcessMaker Platform instance API to which to make all RESTful API calls.
API_TOKEN
Token a Script uses to authenticate to our API host. Note that this API token is only valid for the lifetime of the Script: after the Script runs and the Script Executor's Docker container from which that Script ran, its API token is no longer valid.
Refer to the tabs below how to use variables in supported programming languages.
Below is a sample Script that uses PHP. Refer to the comments denoted with // that describe how the sample functions:
<?php$output = [];// Get a ProcessMaker Platform Environment Variable, in this case TEST_VAR.$output['envVar'] =getenv('TEST_VAR');// Get a value from the config object.// In this example, 'test' in the JSON config: {"test":"test config value"}$output['configTest'] = $config["test"];// Get a value from the data object.// In this example, the user_id for the _request.$output['requestUserId'] = $data['_request']['user_id'];// Get the email address for user id 1 using the API/SDK.// Use the global `$api_config` to set credentials automatically.$usersApi =newProcessMaker\Client\Api\UsersApi(null, $api_config);$user = $usersApi->getUserById("1");$output['userEmail'] = $user->getEmail();return $output;
Below is a sample Script that uses Lua. Refer to the comments denoted with -- that describe how the sample functions:
-- Get a ProcessMaker Platform Environment Variable, in this example TEST_VAR.local envVar =os.getenv("TEST_VAR")-- Get a value from the config object.-- In this example, 'test' in the JSON config: {"test":"test config value"}local configTest = config["test"]-- Get a value from the data object.-- In this example, the user_id for the _request.local requestUserId = data["_request"]["user_id"]-- Get the email address for user id 1 using the API/SDK.-- Use client.make to get a pre-configured api client.-- See https://github.com/ProcessMaker/sdk-lua/tree/master/pmsdk/api for available clients.local users_api = client.make('users_api')local user = users_api:get_user_by_id("1")local userEmail = user.emailreturn {envVar=envVar, configTest=configTest, requestUserId=requestUserId, userEmail=userEmail}
Below is a sample Script that uses JavaScript. Refer to the comments denoted with // that describe how the sample functions:
// A Script written in JavaScript should return a Promise that// resolves with the output data. You can also return a basic object.// For example `return {"key":"value"}`returnnewPromise((resolve, reject) => {// Get a ProcessMaker Platform Environment Variable, in this example TEST_VAR.constenvVar=process.env['TEST_VAR'];// Get a value from the config object.// In this example, 'test' in the JSON config: {"test":"test config value"}constconfigTest= config['test'];// Get a value from the data object.// In this case the user_id for the _request.constrequestUserId= data["_request"]["user_id"];// Get the email address for user id 1 using the API/SDK.// Use the global `api` object to get a pre-configured client.let usersApi =newapi.UsersApi();usersApi.getUserById("1", (error, user) => {constuserEmail=user.email;resolve({'envVar': envVar,'configTest': configTest,'requestUserId': requestUserId,'userEmail': userEmail }); });});
usingSystem;usingProcessMakerSDK.Api;usingProcessMakerSDK.Client;usingProcessMakerSDK.Model;// A Script written in C# must have a 'Script' class that implements 'BaseScript'.// It must include a method named 'Execute'. Results must be added to the 'output' map.publicclassScript:BaseScript{publicoverridevoidExecute(dynamic data,dynamic config,dynamic output,Configuration apiConfig) { // Get a ProcessMaker Platform Environment Variable, in this example TEST_VAR.output.envVar=Environment.GetEnvironmentVariable("TEST_VAR"); // Get a value from the config object. // In this example, 'test' in the JSON config: {"test":"test config value"}output.configTest=config["test"]; // Get a value from the data object. // In this example, the user_id for the _request.output.requestUserId=data["_request"]["user_id"]; // Get the email address for user id 1 using the API/SDK.try {var apiInstance =newUsersApi(apiConfig);Users user =apiInstance.GetUserById("1");output.userEmail=user.Email; } catch (ApiException e) {Console.WriteLine(e.StackTrace); } }}
importjava.io.*;importjava.util.*;importProcessMaker_Client.ApiClient;importProcessMaker_Client.ApiException;importProcessMaker_Model.Users;importProcessMaker_Api.UsersApi;// A Script written in Java must have a 'Script' class that implements 'BaseScript'.// It must include a method named 'execute'. Results must be pushed to the 'output' map.publicclassScriptimplementsBaseScript {publicvoidexecute(Map<String,Object> data,Map<String,Object> config,Map<String,Object> output,ApiClient api ) {// Get a ProcessMaker Platform Environment Variable, in this example TEST_VAR.Map<String,String> env =System.getenv();output.put("env-var",env.get("TEST_VAR"));// Get a value from the config object.// In this example, 'test' in the JSON config: {"test":"test config value"}output.put("config-test",config.get("test"));// Get a value from the data object.// In this example, the user_id for the _request.Map requestData = ((Map)data.get("_request")); output.put("data-request-user-id",requestData.get("user_id"));// Get the email address for user id 1 using the API/SDK.try {UsersApi apiInstance =newUsersApi(api);Users user =apiInstance.getUserById("1");output.put("user-1-email",user.getEmail()); } catch (ApiException e) {e.printStackTrace(); } }}
# A Script written in Python must set a dict# named `output` with the data to return.# Get a ProcessMaker Platform Environment Variable, in this case TEST_VARenvVar = os.getenv('TEST_VAR')# Get a value from the config object.# In this case, 'test' in the json config: {"test":"test config value"}configTest = config['test']# Get a value from the data object.# In this case the user_id for the _requestrequestUserId = data['_request']['user_id']# Get the email address for user id 1 using the API/SDK# Use the global `configuration` object to set auth tokensusers_api_instance = pmsdk.UsersApi(pmsdk.ApiClient(configuration))user = users_api_instance.get_user_by_id(1)userEmail = user.emailoutput ={"envVar": envVar,"configTest": configTest,"requestUserId": requestUserId,"userEmail": userEmail}
# Get a ProcessMaker Platform Environment Variable, in this example TEST_VAR.envVar <-Sys.getenv("TEST_VAR")# Get a value from the config object.# In this example, 'test' in the JSON config: {"test":"test config value"}configVar <- config[["test"]]# Get a value from the data object.# In this example, the user_id for the _request.dataVar <- data[["_request"]][["user_id"]]output<-list(envVar = envVar, configVar = configVar, dataVar = dataVar)
Retrieve All Tasks for a User
The following sample PHP script provides an example to get all Tasks currently assigned to a user. This example also demonstrates the use of optional arguments such as the Request ID or a Task filter.
// Sample PHP script to get all current Tasks for a user<?php$apiInstance = $api->tasks();$tasks = [];// Returns all Tasks that the user has access to$result = $apiInstance->getTasks();foreach ($result->getData()as $task) { $tasks[] = ['id'=> $task->getId(),'name'=> $task->getElementName(),'processRequestId'=> $task->getProcessRequestId(),'status'=> $task->getStatus(),'userId'=> $task->getUserId(), ];}// Optional arguments$process_request_id =5; // int | Process request_id$filter ='Form Task'; // string | filter by Taskid, node name, or Request data$order_by ='id'; // string | Field to order results by$order_direction ='asc'; // string | $include ='process,user'; // string | Include data from related models in payload. Comma separated list.$result = $apiInstance->getTasks($process_request_id, $filter, $order_by, $order_direction, $include);foreach ($result->getData()as $task) { $tasks[] = ['id'=> $task->getId(),'name'=> $task->getElementName(),'status'=> $task->getStatus(),'userEmail'=> $task->getUser()['email'],'processName'=> $task->getProcess()['name'] ];}return ['tasks'=> $tasks];
Get a Task using the Task ID
The following sample PHP script provides an example to retrieve a single Task using its Task ID.
// Sample PHP script to get the Task for a certain TaskID<?php$apiInstance = $api->tasks();$taskId =15;$task = $apiInstance->getTasksById($taskId);return ['task'=> ['name'=> $task->getElementName(),'status'=> $task->getStatus(),'userId'=> $task->getUserId() ]];
Complete a Task
The following sample PHP script provides an example of completing a Task when the Task ID is known.
// Sample PHP Script to complete a Task<?php$apiInstance = $api->tasks();$taskId =15;$task = $apiInstance->getTasksById($taskId);$process_request_token_editable =new\ProcessMaker\Client\Model\ProcessRequestTokenEditable();$process_request_token_editable->setStatus('COMPLETED');$process_request_token_editable->setData(['addToRequestData'=>'a value']);$result = $apiInstance->updateTask($taskId, $process_request_token_editable);// If there are no error, then the Task was successfully completedreturn ['success'=>true];return ['tasks'=> $tasks];