Variable Syntax, Usage, SDK, and Examples

Global Variables

ProcessMaker Platform provides the following two global variables that can be used in Scripts to reference process data.

  • 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 a Script Task, special configurations are entered into the Script Configuration setting. For more information, see Reference a Request Variable from a Script Configuration Setting.

‌Here are some examples of using variables in supported programming languages.

This is a sample Script that uses PHP. Refer to the comments denoted with // that describe how the script works.

  • How to get an Environment Variable.

  • How to get a value from the configuration object.

  • How to get a value from a data object.  Call the Software Development Kit (SDK)

<?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 = new ProcessMaker\Client\Api\UsersApi(null, $api_config);
$user = $usersApi->getUserById("1");
$output['userEmail'] = $user->getEmail();
return $output;

This is a sample Script that uses Lua. Refer to the comments denoted with -- that describe how the script works.

  • How to get an Environment Variable.

  • How to get a value from the configuration object.

  • How to get a value from a data object.

  • Call the Software Development Kit (SDK).

-- 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.email

return {envVar=envVar, configTest=configTest, requestUserId=requestUserId, userEmail=userEmail}

This is a sample Script that uses JavaScript. Refer to the comments denoted with // that describe how the script works.

  • How to get an Environment Variable.

  • How to get a value from the configuration object.

  • How to get a value from a data object.  Call the Software Development Kit (SDK).

// 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"}`
return new Promise((resolve, reject) => {

    // Get a ProcessMaker Platform Environment Variable, in this example TEST_VAR.
    const envVar = process.env['TEST_VAR'];
    
    // Get a value from the config object.
    // In this example, 'test' in the JSON config: {"test":"test config value"}
    const configTest = config['test'];
    
    // Get a value from the data object.
    // In this case the user_id for the _request.
    const requestUserId = 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 = new api.UsersApi();
    usersApi.getUserById("1", (error, user) => {
    
        const userEmail = user.email;
        
        resolve({
            'envVar' : envVar,
            'configTest' : configTest,
            'requestUserId' : requestUserId,
            'userEmail' : userEmail
        });
    });
});

This is a sample Script that uses C#. Refer to the comments denoted with // that describe how the script works.

  • How to get an Environment Variable.

  • How to get a value from the configuration object.

  • How to get a value from a data object.

  • Call the Software Development Kit (SDK).

using System;
using ProcessMakerSDK.Api;
using ProcessMakerSDK.Client;
using ProcessMakerSDK.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.
public class Script : BaseScript
{
    public override void Execute(
        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 = new UsersApi(apiConfig);
            Users user = apiInstance.GetUserById("1");
            output.userEmail = user.Email;
        } catch (ApiException e) {
            Console.WriteLine(e.StackTrace);
        }
    }
}

This is a sample Script that uses Java. Refer to the comments denoted with // that describe how the the script works.

  • How to get an Environment Variable.

  • How to get a value from the configuration object.

  • How to get a value from a data object.  Call the Software Development Kit (SDK).

import java.io.*;
import java.util.*;
import ProcessMaker_Client.ApiClient;
import ProcessMaker_Client.ApiException;
import ProcessMaker_Model.Users;
import ProcessMaker_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.
public class Script implements BaseScript {
    public void execute(
        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 = new UsersApi(api);
            Users user = apiInstance.getUserById("1");
            output.put("user-1-email", user.getEmail());
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }
}

This is a sample Script that uses Python. Refer to the comments denoted with # that describe how the script works.

  • How to get an Environment Variable.

  • How to get a value from the configuration object.

  • How to get a value from a data object.  Call the Software Development Kit (SDK).

import os
from processmaker.client.api.users_api import UsersApi
from processmaker.client.configuration import Configuration
from processmaker.client.api_client import ApiClient

# Initialize the output dictionary
output = {}

# Get a ProcessMaker Platform Environment Variable, in this case TEST_VAR
output['envVar'] = os.getenv('TEST_VAR')

# Get a value from the config object
# Example: 'test' in the JSON config: {"test": "test config value"}
config = {"test": "test config value"}  # Replace with actual config if available
output['configTest'] = config.get("test")

# Get a value from the data object
# Example: user_id for the _request
data = {'_request': {'user_id': 123}}  # Replace with actual data if available
output['requestUserId'] = data.get('_request', {}).get('user_id')

# Get the email address for user ID 1 using the API/SDK
# Use the global `api_config` to set credentials automatically
api_config = Configuration()
api_config.host = "https://your-processmaker-instance.com"  # Replace with your instance URL
api_client = ApiClient(configuration=api_config)
users_api = UsersApi(api_client)

# Fetch user details for user ID 1
user = users_api.get_user_by_id("1")
output['userEmail'] = user.email

# Return the output dictionary
print(output)

Environment Variables

Every Script Executor includes the following default Environment Variables, which a Script can reference to retrieve data.

For more information, see 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.


Magic Variables

ProcessMaker provides the following Magic Variables which can be used to retrieve data about users and requests.

For more information, see Magic Variables and Request Data and JSON

Magic Variable Name

Description

_user.id

A unique identifier for the user. Automatically increments for each created user. This value can be the user that is currently logged on and completing a Form Task/Manual Task.

_user.fax

Fax number as entered into the user's profile.

_user.cell

Cell number as entered into the user's profile.

_user.city

City as entered into the user's profile.

_user.email

Email address as entered into the user's profile.

_user.media

_user.phone

Telephone number as entered into the user's profile.

_user.state

State, region, or province as selected in the user's profile.

_user.title

Job title as entered into the user's profile.

_user.avatar

Image reference for the user's avatar as entered into the user's profile.

_user.postal

Business postal code as entered into the user's profile.

_user.status

Status of the user's account (active or inactive).

_user.address

Business address as entered into the user's profile.

_user.fullname

Full name of the user as entered into the user's profile.

_user.language

Language to display labels as selected in the user's profile.

_user.timezone

Time zone as selected in the user's profile.

_user.username

User name for the user as entered into the user's profile.

_user.birthdate

Birth date for the user. This is not entered into a user profile.

_user.firstname

First name for the user as entered into the user's profile.

_user.created_at

Datetime the user account was created.

_user.deleted_at

Datetime the user account was deleted, if applicable.

_user.expires_at

Datetime the user account expires, if applicable.

_user.updated_at

Datetime the user account was updated, if applicable.

_user.loggedin_at

Datetime the user logged on to the account, if applicable.

_user.datetime_format

Datetime format setting as selected in the user's profile.

_user.is_administrator

Indicates if the user account is granted the Make this user a Super Admin option. true or false values.

Magic Variable Name

Description

_request.id

Request identifier for its associated Process. Automatically increments for each Request instance.

_request.name

Name of the Process associated with the Request.

_request.errors

Contains any errors that occur during the Request.

_request.status

Status of the Request. ACTIVE or INACTIVE values.

_request.user_id

Identifier for the user that created the Process associated with the Request.

_request.created_at

Datetime the user account was create that is associated with the _request.user_id Magic Variable.

_request.process_id

Identifier for the Process associated with the Request. Automatically increments for each created Process.

_request.updated_at

Datetime the Request was updated.

_request.callable_id

Callable identifier for the Process associated with the Request. ProcessId is the value.

_request.completed_at

Datetime the Request completed.

_request.initiated_at

Datetime the Request started.


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 completed
return ['success' => true];
return ['tasks' => $tasks];

Retrieve a Datetime Variable

If a script runs under a different user than the one who started the request and the task involves date variables, automatic detection and formatting of Datetime variables will not occur. Users must manually implement date formatting logic within their scripts.

Here is a sample to retrieve, format, and apply a date format to a Datetime variable using a sample PHP script:

// Retrieve the Datetime variable from the $data array, specifically the value associated with 'updated_at' in '_request'
$dateString = $data["_request"]['updated_at'];

// Create a DateTime object using the Datetime string obtained in the previous line
$date = new DateTime($dateString);

// Define the desired date and time format (Year-Month-Day Hour:Second)
$dateTimeFormat = 'Y-m-d H:s';

// Format the DateTime object according to the defined formatnand assign the result to the $newDate variable
$newDateWithDateFormat = $date->format($dateTimeFormat);