/
Trigger Examples

Trigger Examples

Search the IFS Workflow Wiki
 

Back to Tips and Tricks 

Trigger Examples

Trigger Examples

Starting a Case



ProCount Examples:

ProCount Trigger Important info.txt

Trigger Configuration



Enterprise Upstream Example:

Trigger Configuration

To create a new case in ProcessMaker, you will need to call their REST API. The process consists of three steps:

  1. Authentication.

  2. Creating the case.

  3. Routing The Case. 

The information you need to create the case includes:

  • the UID of the Workflow

  • UID of the starting task you would like to kick off

You can either have these pre-configured in the system, or you may gather the required information through the resources provided in the ProcessMaker REST API.

To view ProcessMakers full API Documentation, see ProcessMaker API documentation.

Authentication

The request needs to be authenticated against their security provider, with the following information:

  • a client ID

  • username

  • password

A recommended approach for automated REST service calls is to have a service account created in the workspace for your product, and then use an impersonate feature to create new workflow cases as a  specific user.

URL: http://{server}/{workspace}/oauth2/token
Example Body:

{
"grant_type": "password",
"scope": "*",
"client_id": "{client_id}",
"client_secret": "{secret}",
"username": "{username}",
"password": "{password}"
}

For more information, see Process Maker access Token documentation.

Creating the Case

Once you have signed in, you can make a POST call to create a case. The input parameters are:

  • Project UID - ID for the workflow

  • Task UID - ID for the starting task since some workflows have multiple starting tasks

  • An array - containing any variables you would like to pre-populate when starting a task.

To impersonate as a specific user, you add impersonate to the URL path and include a user UID for the user you would like to impersonate.

URL: http://{server}/api/1.0/{workspace}/cases/impersonate

Example Body:

{
"pro_uid": "{processId}",
"usr_uid": "{userId}",
"tas_uid": "{taskId}",
"variables":
[{
"var1": "value1",
"var2": "value2"
}]
}

All Three Values can be obtained via running a case in DEBUG mode, these values will display the ProcessID, TaskID, and USR_UID (Note* use the P2Application User for proper configuration)

For more information, see the ProcessMaker New Case documentation.

Routing the Case

The third API call is required to route the case to the first task in the workflow. You must:

  • pass in the app uid (which is the ID of the case you have just created)

  • you should not need to include a body on this request.

URL: http://{server}/api/1.0/{workspace}/cases/{app_uid}/route-case

To help standardize and limit the amount of work needed for a configuration, we have included a group "Automated Services," and it is highly recommended to attach this user group to the target starting task of a process using this trigger. This is due to when the process is exported and imported, we are able to keep that automated services connection, and all users have to do upon an install is assign a user to the group to associate it to all the proper tasks. 

For more information, see the Process Maker Case Routing documentation.

Adding Case Notes

Adding case notes can be a useful tool to track what is happening as a process progresses.  It has the benefits of being able to be read by anyone who has permissions to read the case notes as well as sending an email when the notes are added.

Adding Permissions

To be able to access case notes, users have to be granted permissions within the Workflow Designer.

  1. In IFS Workflow, select the Designer tab.

  2. In the Designer screen, select a workflow, and then click Edit.

  3. In the blue Process Objects dialog box, select Permissions.

  4. On the Permissions screen, click Create.

  5. On the Create permission screen, in Group or User, type in the name that you want to assign permissions.

  6. In Type, you can choose All which includes case notes, or just choose Case Notes.

  7. In Permission, select View.

  8. You can also set the following optional parameters if you don't want the default of All.

  • Case Status - you can restrict access to case notes that are in a specific state:  Draft, To Do, Paused, or Completed

  • Task (Origin and Target) - you can restrict access to case notes that have been approved in one of the following ways: Final Approval, Invoice Approval, POST Approval, Invoice Entered, Invoice Review, Rejected Email

  • Participation Required - you can restrict access to case notes to only users who are participating in the workflow

9. To save your changes, click Save.

Accessing Case Notes

Although there are two ways to access case notes, they both involve clicking on the speech bubble icon

  • From the Home menu: open a list of cases, and then click on the speech bubble

  • From inside a running case: click on the speech bubble on the menu above the DynaForm

  1. Click on the speech bubble icon

    .

  2. The Case Notes screen opens.

  3. Review any previously entered notes.

  4. To add a new note, in the top right hand corner of the screen, click the speech bubble icon with a plus sign

Adding a Note via PHP

There may be a time when you want to add a case note from within a trigger, for example if you want to save the user from manually add notes.  If so, you can add notes using the following code sample.
 

Example PHP: 

$oCaseNotes = new AppNotes();
$message = "This will be the message that gets emailed and added to the notes";
$response = $oCaseNotes->postNewNote(@@APPLICATION, @@USER_LOGGED, $message);

Exporting Documents to a Shared Drive

In some cases, you may need to upload documents from a workflow process to a shared drive on a local windows network.  This requires 2 steps:

  1. The shared drive needs to be setup within the host environment where PM is installed and then mapped to the Windows directory.

  2. The workflow will need to copy the files from the ProcessMaker storage directory to the newly created shared drive.

Host Environment Setup

This step should have already been completed by release management. You can find the configuration steps in the Environment Configuration documentation.

Workflow code

The following PHP code is an example of how we can use a trigger within a workflow to copy all documents associated with a case to the shared drive:

 // Get Case ID - then search for all files attached to case

$caseId = @@APPLICATION;

$query = "SELECT APP_DOC_UID, DOC_VERSION, APP_DOC_TYPE FROM APP_DOCUMENT WHERE APP_UID = '".$caseId."' AND APP_DOC_STATUS = 'ACTIVE' ORDER BY APP_DOC_INDEX";

$aFiles = executeQuery($query);

$path = (new G)->getPathFromUID($caseId);

// If files exist, loop through and add them to shared drive

if (is_array($aFiles) and count($aFiles) > 0) {

    foreach($aFiles as $aFile) {

            $d = new AppDocument();

        $aDoc = $d->Load($aFile['APP_DOC_UID'], $aFile['DOC_VERSION']);

        $filename = $aDoc['APP_DOC_FILENAME'];

        $ext = pathinfo($filename, PATHINFO_EXTENSION);

//Check to see if document is OUTPUT - if so, we need to update some variables - remove this code is all you want is input documents

if ($aFile['APP_DOC_TYPE'] == "OUTPUT"){

$ext = "pdf"; // Set to doc if you want a word '.doc' format

$path .= PATH_SEP. 'outdocs';

$filename .= ".".$ext;

}

        $filePath = PATH_DOCUMENT . $path . PATH_SEP. $aFile['APP_DOC_UID'] . '_' . $aFile['DOC_VERSION'] . '.' . $ext;

//This is the Root of the shared drive on the host system, i.e. where PM is installed - This should only change when the Root changes

$rootDirectory = "/mnt/workflow/";

// Add any sub-directories you want here - can have multiple levels. MUST END WITH "/"

$subDirectory = "testDirectory/";

// Check to see if Directory exists - if not, create it

if (!file_exists($rootDirectory.$subDirectory)) {

mkdir($rootDirectory.$subDirectory, 0700);

}

//Copy file to shared drive

            copy($filePath, $rootDirectory.$subDirectory.$filename);

}

}

Exporting files to FTP with TLS SSL Encryption

It is possible to export files from a workflow to an FTP with TLS/SSL Encryption with the code below.

Note: An FTP server with encryption is different from an SFTP server.

If you are adding an input document through a file/fileupload control on a document control within a ProcessMaker Task, the trigger WILL NOT work if:

  • In the After Dynaform section - the file hasn't been saved to the ProcessMaker Database Table and therefore cannot be found.  

It will work in later sections, in a different dynaform step or the Assignment or Routing steps of the task.

PHP Trigger code:

$conn = ftp_ssl_connect($host, $portNumber );
$login_result = ftp_login ( $conn, $userName , $password );

if($login_result){

    // Run a query to get all documents attached to case
    $caseId = @@APPLICATION;
    $query = "SELECT APP_DOC_UID, DOC_VERSION, APP_DOC_TYPE FROM APP_DOCUMENT WHERE APP_UID = '".$caseId."' AND APP_DOC_STATUS = 'ACTIVE' ORDER BY APP_DOC_INDEX";
    $aFiles = executeQuery($query);

    // If files exist, loop through them and export write them to ftp/s
    if (is_array($aFiles) and count($aFiles) > 0) {
        foreach($aFiles as $aFile) {
            $d = new AppDocument();
            $aDoc = $d->Load($aFile['APP_DOC_UID'], $aFile['DOC_VERSION']);
            $filename = $aDoc['APP_DOC_FILENAME'];
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            $path = (new G)->getPathFromUID($caseId);

            //Check to see if document is OUTPUT - if so, we need to update some variables
            if ($aFile['APP_DOC_TYPE'] == "OUTPUT"){
                $ext = "pdf"; // Set to doc if you want a word '.doc' format
                $path .= PATH_SEP. 'outdocs';
                $filename .= ".".$ext;
            }

            // Path of file to upload
            $filePath = PATH_DOCUMENT . $path . PATH_SEP. $aFile['APP_DOC_UID'] . '_' . $aFile['DOC_VERSION'] . '.' . $ext;

            $fp = fopen($filePath, 'r');
            $remotePath = "/p2app/"; // Root directory of ftp/s server
            $subDirectory = "test/"; // Add subdirectories within the ftp/s - MUST END WITH "/"
            ftp_chdir($conn, $remotePath.$ subDirectory ); // Changes the current directory to the specified one
            // Put file into ftp/s
            if (ftp_fput($conn, $filename, $fp, FTP_ASCII)) {
                $result = "Successfully uploaded $file\n";
            } else {
                $result = "There was a problem while uploading $file\n";
            }

            // close the connection and the file handler
            ftp_close($conn);    
        }
    }
}

Getting an API URL

This section contains an example of the trigger IFS Workflow uses to get the @@apiUrl and @@apiUrlToken from the PMT_EXTERNAL_API table.  We use this table for both security and externalizing where we store the URLs for each product. This is done because if the URL needs to change, then the change only needs to be made in one place, as opposed to changing the URL for each trigger that needs access to the URL in question.

Before using REST endpoints, make sure the information is configured in the PMT_EXTERNAL_API table. For more information about configuring the endpoints, read the Environment Configuration documentation.

In some cases, you might need to connect to more than one system.  If this is the case, the recommend steps are:

  1. Copy the Example code below.

  2. Create new global PM variables (e.g. @@apiUrlBolo & @@apiTokenBolo).

  3. In the majority of cases, the API calls will be made through P2 AppLink and the PMT_EXTERNAL_API record with the ID "P2AppLink" should be used to get the endpoint.

Example

// Pull URL from EXTERNAL API table using the ID of the api you are trying to retrieve.

$apiId = 'P2AppLink';
$urlQuery = executeQuery("SELECT API_URL, TOKEN FROM PMT_EXTERNAL_API WHERE API_ID = '$apiId'");

if (is_array($urlQuery) and count($urlQuery) > 0) {
@@apiUrl = $urlQuery[1]["API_URL"];
@@apiToken = $urlQuery[1]["TOKEN"];
}

else {

    @@errorMessages["API Configuration Error"] = "An API with an ID '".$apiId."' has not been configured properly in External API table";
}

Getting Case Variables

In some cases, you may want to get variables and data from another case, or even a different workflow completely.  There are two methods to achieve this:

  • Using an internal PM Function

  • Creating a Reporting Table

Both of these scenarios achieve the same results.  Which method you should use should really depend on each unique situation. 

  • The PM Function would seem like the quicker, simpler solution to use, but for larger datasets, there might be performance issues due to the results being stored in memory. 

  • Using a report table you can specify exactly what data you want from a case. This provides the added functionality of being able to better filter and query this data via SQL. However, having a extra table does add one more thing to maintain.

Be aware of these issue when using either method, and be sure to test thoroughly. Where possible, add documentation that will help others know what has been done and why.

Example - PM Function

This example includes the following steps:

  1. Get the Case Titles of the New Well Approval workflow.

  2. Use these case titles to get the Case ID of the specific case.

  3. Use this case ID to get the variables.

  4. Populate local text boxes from the data we retrieve.

Task Setup:

  1. In IFS Workflow, select the Designer tab.

  2. In the Designer screen, select a workflow, and then click Edit.

  3. Right-click on a Task, and then select Steps.

  4. On the Steps for a task screen, find the dropdown you want to populate and in that row click Edit.

  5. On the Trigger screen, add the following code:

Use the name of the process to get the variable data from to get the process ID (PRO_UID).

$processName = "New Well Approval"

    // Get the processUid from the name of the process

    $processUid = PMFGetProcessUidByName($processName);

Then, use the process ID to query against a PM table to get the titles (APP_TITLE) and case ID's (APP_UID) of all the New Well Approval workflow, and then populate a dropdown with the results.

// Use a PM Database query to get the titles of all the cases for the New Well Approval workflow
    $query = "SELECT APP_TITLE, APP_UID
    FROM APPLICATION
    WHERE PRO_UID = '".$processUid."'
    ORDER BY APP_TITLE ASC";

    $result = executeQuery($query);

    // Populate a dropdown with the Case Titles and Case ID's
    if (is_array($result) and count($result) > 0) {
        $i = 1;
        foreach($result as $wellInfo){
            @@wellCaseIdArray[$i] = array($wellInfo[APP_UID], $wellInfo[APP_TITLE]);
            $i++;
        }    
    }

This will create a dropdown on a Dynaform that looks like similar to:

Retrieve case variable data and populate local text fields

Use the selected New Well Approval case ID (APP_UID) to retrieve the cases' variable data, then populate some local text box fields with the data.

$c = new Cases();

    $aCase = $c->loadCase(@@seletedWell);

    $caseData = $aCase['APP_DATA'];//APP_DATA is the element of the returned array that contains all the variable data



    // n.b. The array key used will be the name of the variable in the other case

    @@LocalWellName = $caseData['WellName'];

    @@LocalCompletionName = $caseData['CompletionName'];

    @@LocalCompletionType = $caseData['CompletionType'];

    @@LocalCompletionNumber = $caseData['CompletionNumber'];

This will create a 4 text boxeson a Dynaform that looks like similar to:

Example - Reporting Table

This example uses a query a reporting table that is created in the New Well Approval workflow .  For instructions on how to create a reporting table, see the Process Maker Wiki .

Task Setup:

  1. In IFS Workflow, select the Designer tab.

  2. In the Designer screen, select a workflow, and then click Edit.

  3. Right-click on a Task, and then select Steps.

  4. On the Steps for a task screen, find the dropdown you want to populate and in that row click Edit.

  5. On the Trigger screen, add the following code:



Using a REST Service call to get data for ProcessMaker Controls

Wherever possible, IFS Workflow uses REST service calls to retrieve data for use in the various PM Controls, and to save data back within the product's database.

Below are two simple examples of using PHP cURL to connect to a REST api to GET data to populate a Dropdown Control, and POST the data back to the server.

Note: @@apiUrl and @@apiToken are fields that are populated from the EXTERNAL_API table using the Get Api URL trigger. 

Example - Get

The highlighted section is where the actual call to the rest service occurs to get access to the data that the server has made available.  The in-highlighted section is where the data manipulation occurs to get the data in the desired format and into the ProcessMaker variables being used.

$resource_url = @@apiUrl."/api/financial/v1/roles/search/findByPartyUserKeyAndRole?partyUserKey=".@@ownerId."&role=REV&projection=summary";

$ch = curl_init ( $resource_url );

curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );

curl_setopt($ch, CURLOPT_HTTPHEADER, array (

    'Content-Type: application/json',

    'Authorization: Bearer '.@@apiToken

        ) );



$restResponse = curl_exec ( $ch );

$httpResponse = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );

curl_close ( $ch );

if ($httpResponse == 200) {

    $contents = utf8_encode ( $restResponse ); // Convert the string data from the ISO-8859-1 encoding to UTF-8

    $jsonArray = json_decode ( $contents, true ); // Takes a JSON encoded string and convert it into a PHP variable.

    $i = 1; //**Array must start at 1, not 0 to ensure the first element is shown**//

    $roles = $jsonArray ["_embedded"] ["roles"];

    $ownerSitesArray = array(); //**Build a local array with elements**//

    foreach ( $roles as $role ) {

        $ownerSitesArray [$i] = array ($role [' partyId '], $role ['partyUserKeyAndSiteAndName']);

        $i ++;

    }

    @@ownerSites = $ownerSitesArray; //** Set the PM GLobal variable associated with the dropdown we want to populate **//

    }

} else {

    @@errorMessages ['ValidateOwnerIdBody'] = 'Response Body: ' . $restResponse.PHP_EOL.$resource_url;

}

Example - POST

In this example, the extra options are highlighted. This includes options that are set when the REST API is expecting a JSON array. It could also be possible to simply have the data sent as part of the URL, in which case the JSON array of data would not be needed.

$resource_url = @@apiUrl . '/api/financial/v1/revenueBatches/'.$controlCentreUid;    

$curl = curl_init ( $resource_url );

$curl_post_data = array (

    "approval" => "A",

    "lastUpdateDate" => "2017-06-14T16:31:46.000Z",

    "lastUpdatedBy" => "2918",

    "lastUpdateLogin" => "3158551"

); //** The json array of data the service is expecting **//

curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );

curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, ' POST ' ); //** If left out - the default for curl_setopt  is set to GET **//

curl_setopt ( $curl, CURLOPT_POSTFIELDS, json_encode ( $curl_post_data, true ) );

curl_setopt ( $curl, CURLOPT_HTTPHEADER, array (

    'Content-Type: application/json',

    'Authorization: Bearer '.@@apiToken

) );



$response = curl_exec ( $curl );

$httpResponse = curl_getinfo ( $curl, CURLINFO_HTTP_CODE );

curl_close ( $curl );




if ($httpResponse == 200 || $httpResponse == 201) {

    //** If the POST was successful, parse the response and use the returned ID **//

    $contentsUtf8 = utf8_encode ( $response );

    $responseArray = json_decode ( $contentsUtf8, true );

    $distributionProcessID = $responseArray ["id"];

} else {

    @@errorMessages ["PostApprDistPutAppr".$controlCentreUid] = "PostApprDistPutAppr_".$controlCentreUid." ".$response.PHP_EOL.$resource_url;

}



For help troubleshooting errors encountered when working with Triggers, see Trigger Error Handling.


Copyright© 2024 IFS AB. Copying prohibited. All rights reserved.