Reusable Code

A quick copy and paste reference guide

Table of contents


Introduction

This section aims to be a quick copy+paste reference for faster development. If you are adding content to it, please keep in mind the following:

  1. Use Heading 1 style for Tip title, Heading 2 for version. Multiple Heading 2 for same task in different versions under the same Heading 1.
  2. I used to have another suggestion here when I had this as a document on Google Drive, but since I moved it to Confluence, it does not make sense anymore. Anyway, feel free to add other suggestions.

Disable fields, validations and hide fields depending on other fields

Version: 3.0.1.7

Dynaform JavaScript defining a function that alters and hides form controls and registers events
/* Dynaform JavaScript */
function cambioTipoComunicacion (newVal, oldVal) {
  if(newVal == 1) {
    $("#form\\[archivo_comunicacion_entrante\\]").attr("disabled",false);
    $("#archivo_comunicacion_entrante").enableValidation();
    $("#archivo_comunicacion_entrante").show();
    $('#form\\[texto_comunicacion\\]').prop("disabled", true);
    $("#texto_comunicacion").disableValidation();
    $("#texto_comunicacion").hide(); 
  }
  if(newVal == 2) {
    $("#form\\[archivo_comunicacion_entrante\\]").attr("disabled",true);
    $("#archivo_comunicacion_entrante").disableValidation();
    $("#archivo_comunicacion_entrante").hide();
    $('#form\\[texto_comunicacion\\]').prop("disabled", false);
    $("#texto_comunicacion").enableValidation();
    $("#texto_comunicacion").show();
  }
}

$('#tipo_comunicacion').setOnchange(cambioTipoComunicacion);

if( $("#tipo_comunicacion").getValue() != null ) {
  cambioTipoComunicacion( $("#tipo_comunicacion").getValue() );
}

Get mobile signature as image file, use it in output document

Version: 3.0.1.7

Trigger for getting an HTML <img> tag for the signature image file
/* Trigger to get URL to file */
$httpServer = (isset($_SERVER['HTTPS'])) ? 'https://' : 'http://';
// signature0000000001 is the control ID on the form
$signatureImageCustomer = $httpServer.$_SERVER['HTTP_HOST']."/sys".@=SYS_SYS."/".@=SYS_LANG."/".@=SYS_SKIN."/"."cases"."/"."cases_ShowDocument?a=".@=signature0000000001[0];

if(count(@@signature0000000001) > 0)
    @=signatureImgURL = '<img align="middle" src="'.$signatureImageCustomer.'" width="200">';
else
    @=signatureImgURL = '';

 

 

Insertion of HTML <img> tag created by the trigger
<!-- Output document HTML template -->
@=signatureImgURL

Get case number

Version: 3.0.1.7

Trigger to get current case number
$data = executeQuery("SELECT APP_NUMBER FROM APPLICATION WHERE APP_UID = '" . @@APPLICATION . "'"); 
$caseNumber = $data[1]['APP_NUMBER'];

Pass data to webentry form

Version: 3.0.1.7

Modifications to Webentry form
/* This changes belong in the Webentry form file located in /opt/processmaker/shared/sites/{workspace}/public/{process_uid}/{other_uid}.php */
/* Include a file that sets $data array with variables of interest, pass it as APP_DATA argument to pmDynaform*/
include("variables.php");
$a = new pmDynaform(array("CURRENT_DYNAFORM" => "33765576856e30079541c59007526601", "APP_DATA" => $data ) );

 

 

Example variables.php file that create $data array
/* Example variables.php */
$serverName = "172.17.133.49"; //serverName\instanceName
$link = mssql_connect($serverName, 'User_SiaL', 'Icbf2016$');
if (!$link) {
    die('Something went wrong while connecting to MSSQL');
}
$qstr = "SELECT
        IdUsuario,
        NumeroDocumento,
        PrimerNombre,
        SegundoNombre,
        PrimerApellido,
        SegundoApellido,
        CorreoElectronico
FROM
        SIA.SEG.Usuario
WHERE
        IdUsuario =".$_GET['id'];

$res = mssql_query($qstr);
$var = mssql_fetch_assoc($res);
var_dump($var);

$data = array(
        "primer_nombre_denunciante" => $var['PrimerNombre'],
        "segundo_nombre_denunciante" => $var['SegundoNombre'],
        "primer_apellido_denunciante" => $var['PrimerApellido'],
        "segundo_apellido_denunciante" => $var['SegundoApellido'],
        "numero_documento_denunciante" => $var['NumeroDocumento'],
        "correo_electronico_denunciante" => $var['CorreoElectronico'],
);

Email validation regexp (JS)

Version 3.0.1.7

Regular expression matching email addresses. ProcessMaker's default one did not work for me on version 3.0.1.7 for emails like user.name@domain.gov.co
^([A-z0-9\.+\-]+)@([A-z0-9\-]+)\.(([A-z0-9]+)\.)*[A-z0-9]{2,}$

Show new lines from textarea as HTML paragraphs in dynaform view mode

Version 3.0.1.7

JavaScript to change newlines in html <span> element to <p>
var orig = (((($("#texto_respuesta").children()[1]).children)[0]).children[0]).innerHTML;
var fixed = '<p>' + orig.replace(/\n([ \t]*\n)+/g, '</p><p>')
                 .replace('\n', '<br />') + '</p>';
(((($("#texto_respuesta").children()[1]).children)[0]).children[0]).innerHTML = fixed;

Get (UID, NAME) list of departments

Version 3.0.1.7

SQL sentence to get list of departments as defined under ProcessMaker's configuration
select D.DEP_UID, C.CON_VALUE from DEPARTMENT D inner join CONTENT C ON D.DEP_UID = C.CON_ID WHERE C.CON_LANG='en' ORDER BY 2;

Get department and parent department basic information for a given user

Version: 3.0.1.7

This requires customization of the WHERE clause to set the language to be selected from the CONTENT table as well as on the UID of the user whose department and parent department information we want to obtain. Useful for two-level approval.

Get UID and name of a given user department, its manager, the parent department and the parent department's manager
SELECT
    U.DEP_UID AS DUID, 
    PD.DEP_UID AS PDUID, 
    PC.CON_VALUE AS DPNAME,  
    C.CON_VALUE AS DNAME, 
    UD.USR_USERNAME AS DMGRNAME, 
    UPD.USR_USERNAME AS PDMGRNAME,
	UD.USR_UID AS DMGRUID, 
    UPD.USR_UID AS PDMGRUID
FROM 
    USERS U 
    INNER JOIN DEPARTMENT D
     ON D.DEP_UID = U.DEP_UID
    INNER JOIN CONTENT C
     ON C.CON_ID = D.DEP_UID
    INNER JOIN DEPARTMENT PD
     ON PD.DEP_UID = D.DEP_PARENT 
    INNER JOIN CONTENT PC
     ON PC.CON_ID = PD.DEP_UID 
    INNER JOIN USERS UD
     ON UD.USR_UID = D.DEP_MANAGER
    INNER JOIN USERS UPD
	 ON UPD.USR_UID = PD.DEP_MANAGER 
WHERE
    C.CON_LANG='es' 
    AND PC.CON_LANG='es' 
    AND U.USR_UID = 'SOMEUSERUID'

Validate summary column value in grid

Version: 3.0.1.7

Get value of summary column of dynaform grid and validate it of form submittal
/* Need to change first argument of getFormById to match your form, as 
well as grid and column IDs in the definition of variable sum */
getFormById("86976275856f972cb7083d2012193154").el.onsubmit = function () {
  var sum = $("#centros_de_costos_grid").getSummary("porcentaje_centro_costo");
  if(parseFloat(sum) == 100.0)
    return true;
  alert("Sum should be 100");
  return false;
}

Get UID of head of a given department UID

Version: 3.0.1.7

Get the UID of the head/manager user of a given department UID
/* Customize DEP_UID on query */
$qstr = "SELECT * FROM DEPARTMENT WHERE DEP_UID = '45165623356fd76682eae68006745729'";
$res = executeQuery($qstr);
@@dep_manager = $res[1]['DEP_MANAGER'];

 

Get the file's link of previously uploaded files in a grid

Version: 3.0.1.8

The following trigger, it adds values to a Grid where it will show a link to download the file that previously had been uploaded. This trigger is has to be executed before the dynaform.

Trigger to add values to the File UID and the File NAME
//Count the attached files on the grid
$cntGridAttach = 0;
foreach(@@gridAttach as $row){
    @@cntGridAttach++;
}

$sqlSdoc = "SELECT *
                        FROM CONTENT C, (SELECT *
                        FROM APP_DOCUMENT D
                        WHERE D.APP_UID = '".@@APPLICATION."'
                        AND D.APP_DOC_FIELDNAME LIKE '%gridAttach%'
                        ORDER BY D.APP_DOC_INDEX DESC 
                        LIMIT ".@@cntGridAttach.") X
                        WHERE C.CON_ID = X.APP_DOC_UID
                        AND C.CON_CATEGORY = 'APP_DOC_FILENAME'
                        ORDER BY X.APP_DOC_INDEX ASC";
$resSdoc = executeQuery($sqlSdoc);

foreach($resSdoc as $key => $row){
    @@gridAttach[$key]['docUid'] = $row['CON_ID'];    
    @@gridAttach[$key]['docName'] = $row['CON_VALUE'];    
}

 

The following javascript code it has to be added in the Form that displays the link of the files previously uploaded in the grid.

Get the links for the documents
var totalRows = $("#gridAttach").getNumberRows();
for(i=1; i<=totalRows; i++){
    var docUid = document.getElementById("form[gridAttach]["+i+"][docUid]").value;
    var docName = document.getElementById("form[gridAttach]["+i+"][docName]").value;
    document.getElementById("form[gridAttach]["+i+"][linkAttach]").href = "../cases/cases_ShowDocument?a="+docUid;
    document.getElementById("form[gridAttach]["+i+"][linkAttach]").innerHTML = "<center>"+docName+"</center>";
}

Check what processes a user can start and in which task via the REST API

Version: 3.0.2

After authenticating and geting a OAuth2 token, use this endpoing: http://processmaker/api/1.0/workflow/case/start-cases .

Get percentage of completed questions in an Excel RFP

=COUNTA(Range)/<number_of_questions>

Get OAuth2 access token that can be used on the REST API in a dynaform via javascript

http://wiki.processmaker.com/3.0/JavaScript_Functions_and_Methods#PMDynaform.getAccessToken.28.29

Get OAuth2 access token that can be used on the REST API in a trigger

Version: 3.0.2

Get an OAuth2 access token in a trigger, so that it can, for example, be made available to JS via a hidden field in a form:

Store access token in a process variable via PHP Trigger
G::LoadClass('pmDynaform');
$form = new pmDynaform();
@@aToken = $form->getCredentials()[accessToken];

JavaScript code to get case variables via the REST API

Version: 3.0.2

JavaScript function for the GET variables endpoint of a case
function getVariables(baseUrl, aToken, app_uid) {
  var res = $.ajax( {
    url: baseUrl+"/cases/"+app_uid+"/variables", 
    type: "GET", 
    async: false,
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Authorization",'Bearer '+aToken);
    }, 
    data: {}, 
    success: function () {}, 
    error: function () {}, 
  } ).responseJSON;
  return res;
}

JavaScript code to set case variables via the REST API

Version: 3.0.2

Please note that oVars should be a JS object with the same structure that the output of the getVariables() function defined above.

JavaScript function for the PUT variables endpoint of a case
function setVariables(baseUrl, aToken, app_uid, oVars) {
  var res = $.ajax( {
    url: baseUrl+"/cases/"+app_uid+"/variable", 
    type: "PUT", 
    async: false,
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Authorization",'Bearer '+aToken);
    }, 
    data: oVars, 
    success: function () {}, 
    error: function () {}, 
  } ).responseJSON;
  return res;
}

JavaScript code to execute a trigger via the REST API

Version: 3.0.2

JavaScript function for the PUT execute-trigger endpoint
function executeTrigger(baseUrl, aToken, app_uid, tri_uid) {
  var res = $.ajax( {
    url: baseUrl+"/cases/"+app_uid+"/execute-trigger/"+tri_uid, 
    type: "PUT", 
    async: false,
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Authorization",'Bearer '+aToken);
    }, 
    data: {}, 
    success: function () {}, 
    error: function () {}, 
  } ).responseJSON;
  return res;
}

Implementation of a Checkgroup Dependent Field via JavaScript, trigger and REST API

Version: 3.0.2

As of 3.0.2, ProcessMaker dependent fields are not supported for checkgroup form controls. Hence, we manually created the feature by using triggers and REST API calls from within the Dynaform. Refer to this sample process for details: Build_Visit_List-2.pmx .

Implementation of grid Dependent dropdown Fields using variables instead of tables via JavaScript, trigger and REST API

Version: 3.1 RTO

As of 3.1 RTO, ProcessMaker dependent fields on grids are only supported by querying database tables. However, under some scenarios it may be required to implement them from arrays of variables. This sample process gets an array that represents the possible values for the dependent fields depending on the independent field from the variables REST endpoint, then via JS add the corresponding options for each row on the grid. Test_Grid_Ajax_Dependent_fields-1.pmx .

Insert funny characters into eTrial

MySQL
LOAD DATA LOCAL INFILE '/home/Ethan.Presberg/wpg_csvcopy.csv' INTO TABLE PMT_GMINY CHARACTER SET UTF8 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS;

Regex for not allow personal email

^([a-zA-Z0-9_.+-])+\@(163\.com|aol\.com|bellsouth\.net|blueyonder\.co\.??|btconnect\.com|charter\.com|comcast\.net|cox\.net|earthlink\.net|email\.com|gmail\.co|gmail\.com|hotmail\.co\.??|hotmail\.com|juno\.com|mail\.com|mail\.ru|mindspring\.com|msn\.com|ntlworld\.com|orange\.fr|rogers\.com|sbcglobal\.net|shaw\.ca|sympatico\.ca|telus\.net|verizon\.net|virgin\.net|virginmedia\.com|yahoo\.ca|yahoo\.co\.??|yahoo\.com|ymail\.com|icloud\.com|me\.com|mac\.com)+$