Custom Logic Method Reference — $this-> Methods
All custom logic types (API, Event, Validation, Report) share these methods via $this-><method_name>();
IMPORTANT: When generating Custom Logic, Custom API, Custom Event, Custom Validation, or Custom Report code, you may only use these methods and functions from the Custom PHP Whitelist Reference. Any other function call will fail PHP validation.
Data & Queries
$this->query($sql, $bind)
Execute a SQL query and return all rows as an array.
|
Parameter |
Type |
Required |
Description |
|
|---|---|---|---|---|
|
|
|
string |
Yes |
SQL statement using |
|
|
array\ |
null |
No (default |
Associative array mapping placeholder names to values |
Returns: array of rows on success, false on failure. Check $this->getQueryError() after a false return.
Errors logged when: $sql is not a string, or $bind is not an array or null.
// Simple query — no binds
$services = $this->query('SELECT RECID, SERVICE_NAME FROM SERVICES');
if ($services === false) {
$this->debug('Query failed: ' . $this->getQueryError());
} else {
foreach ($services as $row) {
$this->debug($row['SERVICE_NAME']);
}
}
// Query with bind parameters
$status = 'ACTIVE';
$rows = $this->query(
'SELECT RECID, SERVICE_NAME FROM SERVICES WHERE STATUS = :status',
[':status' => $status]
);
// Query with an IN clause using createArrayBinds
$statuses = ['ACTIVE', 'PENDING', 'ON_HOLD'];
$binds = $this->createArrayBinds(':status', $statuses);
$inClause = implode(', ', array_keys($binds));
$rows = $this->query(
"SELECT RECID, SERVICE_NAME FROM SERVICES WHERE STATUS IN ($inClause)",
$binds
);
$this->getQueryError()
Return the error message from the most recent failed query() call.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
(none) |
— |
— |
— |
Returns: string error message, or null if the last query succeeded.
$rows = $this->query('SELECT * FROM NONEXISTENT_TABLE');
if ($rows === false) {
$error = $this->getQueryError();
$this->debug('Query error: ' . $error);
}
$this->createArrayBinds($bindKey, $bindValues)
Convert an array of values into a set of named bind parameters, for use in SQL IN clauses.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
Base name for the bind params (with or without leading |
|
|
array |
Yes |
Array of values to bind |
Returns: array of bind params keyed as :wb_{bindKey}_{n}, or [] on invalid input or empty values.
Errors logged when: $bindKey is not a string, or $bindValues is not an array.
$types = ['COPPER', 'FIBER', 'WIRELESS'];
$binds = $this->createArrayBinds('cable_type', $types);
// Result: [':wb_cable_type_0' => 'COPPER', ':wb_cable_type_1' => 'FIBER', ':wb_cable_type_2' => 'WIRELESS']
$inClause = implode(', ', array_keys($binds));
$rows = $this->query(
"SELECT RECID, CABLE_NAME FROM CABLES WHERE CABLE_TYPE IN ($inClause)",
$binds
);
$this->listGetByCode($type, $code)
Look up a list entry by its type and code.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
List type identifier |
|
|
string |
Yes |
List code value |
Returns: array (the list entry), int, or null if not found.
$entry = $this->listGetByCode('SERVICE_STATUS', 'ACTIVE');
$this->debug('List entry: ' . json_encode($entry));
$this->listFindCode($recid)
Find the code for a list entry by its RECID.
|
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|---|
|
|
int\ |
string |
Yes |
|
Returns: string code value.
$code = $this->listFindCode(42);
$this->debug('Code: ' . $code);
$this->listFindValue($recid)
Find the display value for a list entry by its RECID.
|
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|---|
|
|
int\ |
string |
Yes |
|
Returns: string display value.
$value = $this->listFindValue(42);
$this->debug('Display value: ' . $value);
$this->call($method, $params, $commitOnSuccess)
Call a PCR-360 API shortcut method (e.g., save a contact, save a service).
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
API shortcut name — must be one of the allowed values below |
|
|
array |
Yes |
Parameters passed to the API method |
|
|
bool |
No (default |
Commit the DB transaction immediately on success. Ignored when called from Custom Validation scripts. |
Allowed $method values:
-
renderCableViewPath -
renderCustomReport -
saveCable -
saveContact -
saveEquipment -
saveGla -
saveLocation -
saveService -
saveServiceDesk
Any other value returns ['status' => false, 'message' => '{method} is not a valid call method.'].
Capabilities: The
save*methods can create (insert) or update records — pass aRECIDto update an existing record, omit it to insert a new one. Delete operations are not supported throughcall(); there are nodelete*methods in the whitelist.
Returns: array with at minimum:
-
status—'success'(string) orfalse -
message— description of the result -
params— included on failure
Side effects:
-
Automatically injects a
permissionskey into$paramsbefore dispatch. -
Always clears the aliased class's instance cache via
clearInstances()after the call completes (regardless of success/failure or whether a commit happened).
Errors logged when: $method is not a string, or $params is not an array.
// Save / update a contact
$result = $this->call('saveContact', [
'RECID' => $data['contact_recid'],
'NAME_FIRST' => 'Jane',
'NAME_LAST' => 'Smith',
'EMAIL' => 'jane.smith@example.com',
]);
if ($result['status'] !== 'success') {
$this->debug('saveContact failed: ' . $result['message']);
}
// Save a service desk ticket
$result = $this->call('saveServiceDesk', [
'RECID' => $data['sd_recid'],
'DESCRIPTION' => 'Updated via custom logic',
], true); // commit on success
$this->debug('saveServiceDesk result: ' . $result['status']);
Debugging
$this->debug($data)
Write a value to the Custom Debug table. Output is visible on the Debug tab of the custom logic form.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
mixed |
Yes |
Any value — passed through to the debug writer |
Returns: void
Note: Non-scalar values (arrays, booleans, objects) are serialized by the downstream debug writer. For readable output of booleans and small arrays in your own logs, encode first (e.g.,
json_encode($value)).
// Log a simple string
$this->debug('Processing started');
// Log a variable
$this->debug('Current record: ' . $data['RECID']);
// Log a full array for inspection
$this->debug($data);
// Log the result of a query
$rows = $this->query('SELECT RECID FROM SERVICES WHERE STATUS = :s', [':s' => 'ACTIVE']);
$this->debug('Active service count: ' . count($rows));
Events
$this->callCustomEvent($identifier, $data)
Trigger another custom event by its identifier, passing data to it.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
The identifier of the custom event to call |
|
|
array |
Yes |
Data array passed to the called event (merged with context) |
Returns: string, array, bool, or null — whatever the called event returns. Returns null and logs an error if either parameter is the wrong type.
Warning — reserved keys silently overwritten: The following keys in
$dataare always overwritten before the call:
custom_identifier— set to the$identifierpassed in
called_by_custom_identifier— set to{callingClass}:{previousIdentifier}
checkStatus— forced totrueDo not rely on your own values for these keys.
Errors logged when: $identifier is not a string, or $data is not an array.
// Trigger a notification event after processing
$result = $this->callCustomEvent('send-service-notification', [
'service_recid' => $data['RECID'],
'trigger' => 'status-change',
'new_status' => 'ACTIVE',
]);
$this->debug('Notification event returned: ' . json_encode($result));
File Operations
$this->createFile($filename, $content, $location, $overwrite)
Write a file to the INBOUND or OUTBOUND directory.
|
Parameter |
Type |
Required |
Description |
|
|---|---|---|---|---|
|
|
string |
Yes |
Filename only — any path separators are stripped via |
|
|
|
string\ |
array |
Yes |
File content. Arrays are concatenated with no separator (PHP's |
|
|
string |
No (default |
|
|
|
|
bool |
No (default |
Overwrite if the file already exists |
|
Returns: int bytes written on success, false on failure.
Note: The target directory is created automatically (
mkdir(..., 0777, true)) if it does not exist.
// Write a plain text file to OUTBOUND
$bytes = $this->createFile('export-summary.txt', 'Export complete. 42 records processed.');
if ($bytes === false) {
$this->debug('File write failed');
} else {
$this->debug("Wrote $bytes bytes");
}
// Build a CSV and write it to OUTBOUND
$rows = $this->query('SELECT SERVICE_NAME, STATUS, MONTHLY_COST FROM SERVICES');
$csv = $this->arrayToCsv(['Service Name', 'Status', 'Monthly Cost']);
foreach ($rows as $row) {
$csv .= $this->arrayToCsv($row);
}
$this->createFile('services-export.csv', $csv, 'OUTBOUND', true);
// Write JSON — encode explicitly, do not rely on auto-encoding
$payload = ['count' => 42, 'items' => $items];
$this->createFile('export.json', json_encode($payload), 'OUTBOUND', true);
$this->arrayToCsv($data, $delimiter, $enclosure)
Convert a flat array into a single CSV row string.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
array |
Yes |
Flat array of values representing a single CSV row |
|
|
string |
No (default |
Column separator |
|
|
string |
No (default |
Value quoting character |
Returns: string — CSV row on success, '' on invalid input.
Errors logged when: $data is not an array.
// Single row
$csv = $this->arrayToCsv(['Alice Brown', '1001', 'Engineering']);
// "Alice Brown",1001,Engineering
// Multiple rows — loop and concatenate
$rows = [
['Name', 'Extension', 'Department'],
['Alice Brown', '1001', 'Engineering'],
['Bob Jones', '1002', 'Finance'],
];
$csv = '';
foreach ($rows as $row) {
$csv .= $this->arrayToCsv($row);
}
$this->createFile('directory.csv', $csv);
// Pipe-delimited
$csv = '';
foreach ($rows as $row) {
$csv .= $this->arrayToCsv($row, '|');
}
$this->readFile($filename, $location, $offset, $length)
Read the contents of a file from the INBOUND or OUTBOUND directory.
|
Parameter |
Type |
Required |
Description |
|
|---|---|---|---|---|
|
|
string |
Yes |
Filename only — path separators are stripped via |
|
|
|
string |
No (default |
|
|
|
|
int |
No (default |
Byte offset to start reading from |
|
|
|
int\ |
null |
No (default |
Max bytes to read; |
Returns: string file contents on success, false on failure.
Errors logged when: $filename is not a string, $length is not an integer or null, or $location is not INBOUND/OUTBOUND.
// Read a full file from INBOUND
$content = $this->readFile('import-data.txt', 'INBOUND');
if ($content === false) {
$this->debug('Could not read file');
} else {
$lines = explode("\n", $content);
$this->debug('Line count: ' . count($lines));
}
// Read only the first 512 bytes
$preview = $this->readFile('large-export.txt', 'OUTBOUND', 0, 512);
$this->debug('File preview: ' . $preview);
$this->readCsvFile($filename, $location, $hasHeader, $length, $delimiter, $enclosure, $escape)
Read a CSV file and return its rows as an array.
|
Parameter |
Type |
Required |
Description |
|
|---|---|---|---|---|
|
|
string |
Yes |
Filename only — path separators are stripped |
|
|
|
string |
No (default |
|
|
|
|
bool |
No (default |
If |
|
|
|
int\ |
null |
No (default |
Max bytes per row; |
|
|
string |
No (default |
Column separator |
|
|
|
string |
No (default |
Value quoting character |
|
|
|
string |
No (default |
Escape character |
|
Returns: array of rows on success, false on failure. Rows are associative arrays when $hasHeader is true, indexed arrays otherwise.
Warning: When
$hasHeaderistrue, any data row whose column count does not match the header count is silently skipped (an error is logged but no exception is raised). The returned array will omit mismatched rows.
Errors logged when: $filename is not a string, $length is not an integer or null, or $location is not INBOUND/OUTBOUND.
// Read a CSV with headers from INBOUND
$rows = $this->readCsvFile('new-contacts.csv', 'INBOUND');
if ($rows === false) {
$this->debug('Could not read CSV');
} else {
foreach ($rows as $row) {
// $row keys match the header row: $row['First Name'], $row['Email'], etc.
$result = $this->call('saveContact', [
'NAME_FIRST' => $row['First Name'],
'NAME_LAST' => $row['Last Name'],
'EMAIL' => $row['Email'],
]);
$this->debug('Imported: ' . $row['First Name'] . ' — ' . $result['status']);
}
}
// Read a CSV without headers (rows are indexed arrays)
$rows = $this->readCsvFile('raw-data.csv', 'INBOUND', false);
foreach ($rows as $row) {
$this->debug('Col 0: ' . $row[0] . ', Col 1: ' . $row[1]);
}
HTTP / cURL
$this->curlRequest($url, $requestOptions, $closeCurl, $debug)
Make an HTTP or HTTPS request. SFTP is not supported.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
Full HTTP or HTTPS URL |
|
|
array |
Yes |
Structured associative array — see keys below |
|
|
bool |
No (default |
Close the cURL handle after execution; set |
|
|
bool |
No (default |
Include curl info and resolved options in the return value |
$requestOptions keys:
|
Key |
Type |
Description |
|---|---|---|
|
|
string |
|
|
|
array |
Request parameters. For |
|
|
array |
Associative array of header name → value. See Content-Type note below. |
|
|
array |
Associative array of cookie name → value. Sent as a single |
|
|
array |
Raw |
Important — Content-Type is forced: This wrapper always sends
Content-Type: application/x-www-form-urlencoded. AnyContent-Typekey you supply inheadersis silently dropped. If you need to send a JSON body or any other content type, you must use the lower-levelcurl_init(),curl_setopt(), and$this->curlExec()helpers instead.
Also enforced at exec time:
CURLOPT_RETURNTRANSFERis alwaystrue, andCURLOPT_PROTOCOLSis locked to HTTP/HTTPS/SFTP.curlRequestadditionally rejects any URL starting withs<ftp://> via a separate URL-scheme guard — if you need SFTP, use the lower-levelcurl_init()/curl_setopt()/$this->curlExec()helpers instead.
Returns: array with keys:
-
success(bool) —truefor HTTP 2xx responses -
response(string) — response body (on success) -
errors(array) — error messages (on failure; key is removed on success) -
debug(array) — curl info and options (only when$debugistrue) -
curlHandle— the curl resource (only when$closeCurlisfalse)
Errors logged when: $url is not a string, or $requestOptions is not an array.
// Simple GET request
$result = $this->curlRequest('https://api.example.com/status', [
'httpMethod' => 'GET',
'params' => ['format' => 'json'],
'headers' => ['Accept' => 'application/json'],
'curl' => [
CURLOPT_TIMEOUT => 10,
],
]);
if ($result['success']) {
$body = json_decode($result['response'], true);
$this->debug('API status: ' . $body['status']);
} else {
$this->debug('Request failed: ' . implode(', ', $result['errors']));
}
// POST request (form-encoded — Content-Type cannot be overridden)
$result = $this->curlRequest('https://api.example.com/services', [
'httpMethod' => 'POST',
'params' => [
'service_id' => 1234,
'action' => 'activate',
],
'headers' => [
'Authorization' => 'Bearer ' . $apiToken,
],
'curl' => [
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true,
],
]);
$this->debug('POST result: ' . json_encode($result['success']));
// Calling another PCR-360 Custom API (API key is embedded in the URL — no auth header needed)
$result = $this->curlRequest(
'https://pcr360.example.com/api/{API_KEY_TOKEN}/get_dept_from_gl.json',
[
'httpMethod' => 'POST',
'params' => ['account_number' => $gl],
'curl' => [
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true,
],
]
);
Messaging
$this->sendSystemMessage($subject, $messageText, $recipientContactsRecid, $logicIdentifier)
Send a PCR-360 system message to a contact.
|
Parameter |
Type |
Required |
Description |
|
|---|---|---|---|---|
|
|
string |
Yes |
Message subject line |
|
|
|
string |
Yes |
Message body |
|
|
|
string\ |
int |
Yes |
|
|
|
string |
No (default |
Identifier of the calling custom logic (used for audit/logging) |
|
Returns: bool — true if the message was created successfully, false otherwise.
Note — auto-appended footer: A footer is automatically appended to
$messageText:\\n\\nGenerated From: {customerName} {logicType}: {identifier}wherelogicTypecomes from the calling custom logic class's$customLogicTypeproperty (e.g.,'Custom Validation','Custom Report'), falling back to'Custom Logic'when not set.
Errors logged when: $recipientContactsRecid is not a string or numeric.
// Notify a contact when a service goes active
$rows = $this->query(
'SELECT OWNER_RECID FROM SERVICES WHERE RECID = :recid',
[':recid' => $data['RECID']]
);
if (!empty($rows)) {
$ownerRecid = $rows[0]['OWNER_RECID'];
$sent = $this->sendSystemMessage(
'Your service is now active',
'Service #' . $data['RECID'] . ' has been activated as of ' . date('Y-m-d') . '.',
$ownerRecid,
'service-activation-notify'
);
$this->debug('Message sent: ' . json_encode($sent));
}
Validation (Custom Validation scripts only)
$this->setMessage($message, $messageKey)
Set a validation failure message. Always return false; after calling this.
|
Parameter |
Type |
Required |
Description |
|
|---|---|---|---|---|
|
|
|
string |
Yes |
The message displayed to the user on validation failure |
|
|
string\ |
null |
No (default |
Message key used by the validator |
Returns: self (fluent) — can be chained.
if (empty($data['EMAIL'])) {
$this->setMessage('Email address is required.');
return false;
}
$this->setError($message)
Add an error message to the validation result. Side effect: marks the validator as invalid (calls _error(self::ERROR) internally).
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
Error message text |
Returns: self (fluent) — can be chained.
if (!preg_match('/^[^\s@]+@[^\s@]+\.[^\s@]+$/', $data['EMAIL'])) {
$this->setError('The email address "' . $data['EMAIL'] . '" is not valid.');
return false;
}
$this->setWarning($message)
Add a warning message to the validation result (does not block the save). Side effect: calls _error(self::WARNING) internally.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
Warning message text |
Returns: self (fluent) — can be chained.
if (strlen($data['NOTES']) > 500) {
$this->setWarning('Notes are very long and may be truncated in some views.');
}
Reports (Custom Report scripts only)
$this->assign($name, $value)
Assign a variable to the Smarty report template.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
Smarty template variable name |
|
|
mixed |
Yes |
Value to assign |
Returns: void
$rows = $this->query(
'SELECT SERVICE_NAME, STATUS, MONTHLY_COST FROM SERVICES WHERE GLA_RECID = :gla',
[':gla' => $params['gla_recid']]
);
$this->assign('services', $rows);
$this->assign('report_date', date('Y-m-d'));
$this->assign('total_cost', array_sum(array_column($rows, 'MONTHLY_COST')));
$this->addError($message)
Add an error message to the report output.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
Error message text |
Returns: void
if (empty($params['gla_recid'])) {
$this->addError('A GLA is required to run this report.');
return;
}
$this->loadReport($identifier, $params)
Load and execute another custom report, returning its rendered output.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
Identifier of the custom report to load |
|
|
array |
Yes |
Parameters passed to the loaded report |
Returns: string — the rendered report HTML.
Side effect: The sub-report's Smarty assigns and errors are merged into the calling report (via
addAssigns/addErrors).
$subreport = $this->loadReport('service-cost-summary', [
'gla_recid' => $params['gla_recid'],
'start_date' => $params['start_date'],
]);
$this->assign('cost_summary', $subreport);
$this->barcode($code)
Generate a barcode image HTML snippet for embedding in a report.
|
Parameter |
Type |
Required |
Description |
|---|---|---|---|
|
|
string |
Yes |
The value to encode in the barcode |
Returns: string — HTML <img> tag for the barcode.
Note: Barcode format/type is not configurable through this helper — the view helper controls the format.
$barcode = $this->barcode($data['ASSET_TAG']);
$this->assign('asset_barcode', $barcode);