Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

This server class provides methods to operate with database records.

SimpleRecord(tableName)


Instantiates This method instantiates a SimpleRecord class object for the a particular table specified.


Parameter(s):

NameTypeMandatoryDefault Value
tableNameStringYN''

Example:

Code Block
languagejs
themeEclipse
titleSimpleRecord
linenumberstrue
let sysNumber = '';
sysNumber += subject.match(/[A-Z]+\d+/g);
if (!!sysNumber) {
  const taskconst taskRecord = new SimpleRecord('task');
  task.get('number', sysNumber);
  if (!!task.sys_id) {
    task.state = '10'; // Cancelled  
    task.update();
  }
}

addOrCondition(property, operatorOrValue, value)

This method appends a 2-or-3 parameter OR condition to an existing query. It works in conjunction with any of the addQuery() methods.

Parameter(s):

NameTypeMandatoryDefault ValuepropertyStringYNoperatorOrValueInteger or String or Boolean (if this parameter is used as a value); String (if this parameter is used as an operator).NNvalueInteger or String or BooleanNNULL


REM attribute object


The SimpleRecord class has a special object for Record Extended Modelsrem_attr – containing information about the REM attributes. It is used to read and edit REM attributes values of the current record with other class methods as in the example below.

Tip

rem_attr has a number of methods equal to methods of the SimpleRecord: 

For example:

record.rem_attr.getValue('my_rem_attribute');

Parameter:

NameTypeMandatoryDefault Value
propertyStringYN

Return:

TypeDescription
SimpleRecord objectThis method returns the SimpleRecord object from the defined RE model.
The method returns null if the record does not have a RE model.

Example:

Code Block
languagejs
themeEclipse
titleget using REM
linenumberstrue
const record = new SimpleRecord('task');
record.get('160638931615274614');
if (record.getReModelId()) {
    ss.info(record.rem_attr.description);
}

addOrCondition(property, operator, value)


This method appends a 2-or-3 parameter OR condition to an existing query. It works in conjunction with any of the addQuery() methods. In this method, you can use any preferred operator from the Condition Operators list, specified either in lowercase or in uppercase. Notice that you need to use the system name of the operator in your scripts.

You can also specify a RE model attribute of a specific table. To filter records, use the operators corresponding to the attribute type.

Note

The condition may contain criteria based on the attribute of different RE models. If such criteria are built using the AND operator, the selection of records will be empty. To return records that match a condition, use the OR operator.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringY

N

Info

For the REM attributes use the following pattern:

'<sys_id>:<attr_name>' 

where sys_id – the ID of the model that contain the attribute, and attr_name – the system name of the REM attribute.


operatorString (refer to the Condition Operators article for more information)NN
valueInteger, String, Boolean, Array or SimpleRecord objectYN


Return:

TypeDescription
SimpleRecordThe query containing OR condition added to the SimpleRecord object.


Examples:

Code Block
languagejs
themeEclipse
titleaddOrCondition
linenumberstrue
const record = new SimpleRecord('task');
record.addQuery('subject', 'like', 'not work')
record.addOrCondition('description', 'like', 'not work');
ss.info('Condition query: ' + record.getConditionQuery());
record.query();
// Info: Condition query: (subjectLIKEnot work)^OR(descriptionLIKEnot work)


Code Block
languagejs
themeEclipse
titleaddOrCondition with REM attribute
linenumberstrue
let record = new SimpleRecord('task');
record.addQuery('subject', 'like', 'not work')
record.addOrCondition('166972638116358001:description', 'contains', 'not work');
ss.info('Condition query: ' + record.getConditionQuery());
record.query();
// Info: Condition query: (subjectLIKEnot work)^OR(166972638116358001:descriptionLIKEnot work)


Info

It is possible to pass the SimpleRecord object as current.{reference_field_name} instead of the record ID as the addOrCondition() method value. The script example:

Code Block
languagejs
themeEclipse
titlePassing SimpleRecord as an argument
linenumberstrue
collapsetrue
const task = new SimpleRecord('task');
task.setLimit(1);
task.query();
if (!task.next()) {
  ss.info('No tasks found!');
  return;
}

const relatedTask = new SimpleRecord('task');
relatedTask.addQuery('caller', task.caller);
relatedTask.addOrCondition('assigned_user', task.caller);
relatedTask.query();
ss.info('Tasks count: ' + relatedTask.getRowCount());
// Info: Tasks count: 122



addQuery(property, operator, value)


This method adds a condition to make a selection of records from the database. In this method, you can use any preferred operator from the Condition Operators list, specified either in lowercase or in uppercase. Note that you need to use system name of the operator in your scripts.

You can also specify a RE model attribute of a specific table. To filter records, use the operators corresponding to the attribute type. 

Note

The condition may contain criteria based on the attribute of different RE models. If such criteria are built using the AND operator, the selection of records will be empty. To return records that match a condition, use the OR operator.

Parameter(s):

NameTypeMandatoryDefault Value
propertyStringY

N

Info

For the REM attributes use the following pattern:

'<sys_id>:<attr_name>'

where sys_id – the ID of the model that contain the attribute, and attr_name – the system name of the REM attribute.


operatorString (refer to the Condition Operators article for more information)NN
valueInteger or String or Boolean or Array or SimpleRecord objectYN


Return:

TypeDescription
SimpleRecordThe query condition added to the SimpleRecord object.


Examples:

Code Block
languagejs
themeEclipse
titleaddQuery
linenumberstrue
const task = new SimpleRecord('task');
task.addQuery('active', true);
task.addQuery('subject', 'like', 'email');
task.addQuery('sys_created_at', '<', '2019-04-01 00:00:00');
task.query();
ss.info('Count: ' + task.getRowCount());
// Info: Count: 0


Code Block
languagejs
themeEclipse
titleaddQuery with REM attribute
linenumberstrue
let record = new SimpleRecord('task');
record.addQuery('166972638116358001:description', 'not work');
record.query();
ss.info("Total rows: " + record.getRowCount());
// Info: Total rows: 1


Info

It is possible to pass the SimpleRecord object as current.{reference_field_name} instead of the record ID as the method addQuery() value. The script example:

Code Block
languagejs
themeEclipse
titlePassing SimpleRecord as an argument
linenumberstrue
collapsetrue
const task = new SimpleRecord('task');
task.setLimit(1);
task.query();
if (!task.next()) {
  ss.info('No tasks found!');
  return;
}

const otherTask = new SimpleRecord('task');
otherTask.addQuery('caller', task.caller);
otherTask.addQuery('sys_id', '!=', task.sys_id);
otherTask.query();
ss.info('Tasks count: ' + otherTask.getRowCount());
// Info: Tasks count: 720



addEncodedQuery(condition)


This method adds encoded query and applies it to the current query method.

Info

Decoded query is also applicable.

You can also specify a RE model attribute of a specific table. To filter records, use the operators corresponding to the attribute type. 

Note

The condition may contain criteria based on the attribute of different RE models. If such criteria are built using the AND operator, the selection of records will be empty. To return records that match a condition, use the OR operator.

Use curly brackets when setting a filter argument for the text fields of type String, Text, Translated Text, Conditions, and URL. Using parenthesis for the argument may cause a filter query error.

Code Block
languagejava
themeEclipse
titleFilter with text fields
linenumberstrue
collapsetrue
const subject = 'Hello, SimpleOne)';
const task = new SimpleRecord('task');
task.addEncodedQuery(`subjectLIKE${subject}`);
ss.info(task.getConditionQuery());
try {
    task.query();
} catch (e) {
   ss.error(e.message);
} 
// Info: (subjectLIKEHello, SimpleOne))
// Error: Condition query is invalid

Parameter(s):

NameTypeMandatoryDefault Value
conditionString Y

N

Info

For the REM attributes use the following pattern:

'<sys_id>%3A<attr_name>'

where sys_id – the ID of the model that contain the attribute, and attr_name – the system name of the REM attribute.



Return:

TypeDescription
VoidThis method does not return a value.


Examples:

Code Block
languagejs
themeEclipse
titleaddEncodedQuery
linenumberstrue
const currentUser = ss.getUser();
const receiver = new SimpleRecord('employee');
receiver.addQuery('active', true);
if (currentUser.company.class === 'internal') {
    receiver.addEncodedQuery(`(company=${currentUser.getValue('company')})`);
} else {
    receiver.addEncodedQuery(`%28sys_db_table_id%3D158645243815904649%5Esys_created_byDYNAMIC156957117519820256%29`);
}
ss.info('Decoded condition: ' + receiver.getConditionQuery());
receiver.query();
// Info: Decoded condition: (active=1)^((sys_db_table_id=158645243815904649^sys_created_byDYNAMIC156957117519820256))


Code Block
languagejs
themeEclipse
titleaddEncodedQuery with REM attributes
linenumberstrue
const receier = new SimpleRecord('task');
receiver.addQuery('active', true);
receiver.addEncodedQuery('%28sys_db_table_id%3D158645243815904649%5E166972638116358001%3AdescriptionLIKEwork`);
ss.info('Decoded condition: ' + receiver.getConditionQuery());
receiver.query();
// Info: Decoded condition: (active=1)^((sys_db_table_id=158645243815904649^166972638116358001:descriptionLIKEwork))

canCreate()


This method checks whether inserting new records in this table satisfies the Access Control Rule (ACL).

Also, you can use this method in your UI Actions to adjust its visibility more precisely.


Return:

TypeDescription
BooleanThe method returns 'true' if this operation is permitted; otherwise, it returns 'false'.


Example:

Code Block
languagejs
themeEclipse
titlecanCreate
linenumberstrue
current.canCreate();

canDelete()


This method checks whether deleting records in this table satisfies the Access Control Rule (ACL).

Also, you can use this method in your UI Actions to adjust its visibility more precisely.


Return:

TypeDescription
BooleanThe method returns 'true' if this operation is permitted; otherwise, it returns 'false'.


Example:

Code Block
languagejs
themeEclipse
titlecanDelete
linenumberstrue
current.canDelete();

canRead()


This method checks whether reading records in this table satisfies the Access Control Rule (ACL).

Also, you can use this method in your UI Actions to adjust its visibility more precisely.


Return:

TypeDescription
BooleanThe method returns 'true' if this operation is permitted; otherwise, it returns 'false'.


Example:

Code Block
languagejs
themeEclipse
titlecanRead
linenumberstrue
current.canRead();


canUpdate()


This method checks whether updating records in this table satisfies the Access Control Rule (ACL).

Also, you can use this method in your UI Actions to adjust its visibility more precisely.


Return:

TypeDescription
BooleanThe method returns 'true' if this operation is permitted; otherwise, it returns 'false'.


Example:

Code Block
languagejs
themeEclipse
titlecanUpdate
linenumberstrue
current.canUpdate();

deleteMultiple()


This method allows deleting multiple records in a query selection. Please note that attachments cannot be deleted using this method.

Note

Do not use this method on tables with dependencies. Always delete each record individually.


Return:

TypeDescription
BooleanThis method returns 'true' if records are deleted successfully; otherwise, it returns 'false'.


Example:

Code Block
languagejs
themeEclipse
titledeleteMultiple
linenumberstrue
const record = new SimpleRecord('sys_activity_feed_item');
record.addQuery('content', 'isempty');
record.query();
ss.info(record.getRowCount());
ss.info(record.deleteMultiple());
// Info: 0
// Info: true


deleteRecord()


This method deletes the current record.


Return:

TypeDescription
BooleanThis method returns 'true' if the record is deleted successfully; otherwise it returns 'false'.


Example:

Code Block
languagejs
themeEclipse
titledeleteRecord
linenumberstrue
const task = new SimpleRecord('task');
task.get('155931135900000000');
if (!task.sys_id) {
  return;
}
const isDeleted = task.deleteRecord();
if (isDeleted) {
  ss.info('Task with ID ' + task.sys_id + ' was deleted!');
  return;
}
ss.error(task.getErrors());


get(propertyOrValue, value)


This method loads an object from a database by the field value, or, in a specific case, by the sys_id.


Parameter(s):

NameTypeMandatoryDefault Value
propertyOrValue

String value of record ID or property name. If it is equal to the property name, then the second parameter 'value' is mandatory.

Note

Passing 'NULL' or an empty string as the propertyOrValue parameter value causes an exception:

"Argument 1 passed to "get()" must not be empty".


YN
valueString or SimpleRecord objectNNULL


Return:

TypeDescription
SimpleRecord objectThis method returns a SimpleRecord object from the table specified in the query.


Example:

Code Block
languagejs
themeEclipse
titleget
linenumberstrue
const task = new SimpleRecord('task');
task.get('163663310116371174'); // get by ID

if (task.state == '18') { // Rejected
  const company = new SimpleRecord('org_company');
  company.get('c_website', task.c_customer_url); // get by Customer URL
  ss.eventQueue('notify.responsible', task, company.responsible.email);
}


Info

It is possible to pass the SimpleRecord object as current.{reference_field_name} instead of the record ID as the get() method value. The script example:

Code Block
languagejs
themeEclipse
titlePassing SimpleRecord as an argument
linenumberstrue
collapsetrue
const task = new SimpleRecord('task');
task.setLimit(1);
task.query();
if (!task.next()) {
  ss.info('No tasks found!');
  return;
}

const user = new SimpleRecord('user');
user.get(task.caller);
user.language_id = '156628684306541141'; // English
ss.info(user.update());
// Info: 167515292501757147



getAttributes()


This method returns an object with current record properties as keys and properties values as key values.


Return:

TypeDescription
ObjectThe array containing attributes.


Code Block
languagejs
themeEclipse
titlegetAttributes
linenumberstrue
const userRecord = ss.getUser();
ss.info(userRecord.getAttributes());
// Info: {"sys_id":"155931135900000001","sys_created_at":"2019-09-30 00:00:00","sys_updated_at":"2021-06-28...

getClassDisplayValue()


This method returns the table title. If the title is not set, then returns name.


Return:

TypeDescription
StringTitle or name.


Example:

Code Block
languagejs
themeEclipse
titlegetClassDisplayValue
linenumberstrue
const current = new SimpleRecord('task');
current.get('163663310116371174');
ss.info(current.getClassDisplayValue());
// Info: Task

getConditionQuery()


This method returns current query condition.


Return:

TypeDescription
StringThe query condition

Return:

TypeDescriptionSimpleRecordThe query containing OR condition added to the SimpleRecord object
.


Example:

Code Block
languagejs
themeEclipse
titleaddOrConditiongetConditionQuery
linenumberstrue
const task = new SimpleRecord('task');
const taskcondition = new SimpleRecord('tasktask.addQuery('state', '7');
taskcondition.addQueryaddOrCondition('subjectpriority', 'like<', 'not work').addOrCondition('description', 'like', 'not work');
task.query();
task.setMultipleValue('attention_required', '1');
task.updateMultiple();

addQuery(property, operatorOrValue, value)

This method adds a condition for the selection from the database. In this method, you can use any preferred operator from the Condition Operators list, specified either in lowercase or in uppercase
'3');
ss.info('Condition before query: ' + task.getConditionQuery());
task.query();
ss.info('Condition after query: ' + task.getConditionQuery());
// Info: Condition before query: (state=7)^OR(priority<3)
// Info: Condition after query:

getDisplayValue(property) 
Anchor
getDisplayValue()
getDisplayValue()


This method returns the value of display_by_ref field or record value. For example, for the reference field the entity name will be returned, but not the ID.


Parameter(s):

NameTypeMandatory
Default ValuepropertyStringYNoperatorOrValueInteger or String or Boolean (if this parameter is used as a value); String (if this parameter is used as an operator).NNvalue
Default Value
PropertyString
Integer or String or Boolean
NNULL


Return:

TypeDescription
SimpleRecordThe query condition added to the SimpleRecord object
StringA field or record value.


Example:

Code Block
languagejs
themeEclipse
titleaddQuerygetDisplayValue
linenumberstrue
const taskcurrent = new SimpleRecord('task');
task.addQuery('active', true);
task.addQuery('subject', 'like', 'сеть');
task.addQuery('sys_created_at', '<', '2019-04-01 00:00:00current.get('163663310116371174');
task.query(ss.info(current.getDisplayValue('caller'));
ss.info('Count: ' + task.getRowCount());

addEncodedQuery(condition)

Adds encoded query to other queries already created.

Parameter(s)

(current.getValue('caller'));
// Info: John Doe
// Info: 155931135900000001

getErrors() 
Anchor
getErrors
getErrors


If the record creating, updating or deleting fails, then this method will display an error message.

Use this method for control purposes if there any validation errors within your scripts.

Warning

Some validation errors may not be displayed within the debug process, so it is highly recommended to use this method.

For example, errors in condition queries passed by methods like addEncodedQuery(condition) or similar methods can be displayed by calling this method.


NameTypeMandatoryDefault ValueconditionStringYN

Return:

TypeDescription
VoidThis method does not return a
ArrayThe error value.


Example:

Code Block
languagejs
themeEclipse
titleaddEncodedQuerygetErrors
linenumberstrue
const employeerecord = new SimpleRecord('employee');
employee.addEncodedQuery('%28locked_out%21%3D0%29%5EmanagerISEMPTY');
employee.query();
employee.setMultipleValue('locked_out', '0');
employee.updateMultiple();

canCreate()

This method determines if the Access Control Rules permit inserting new records in this table.

Return:

TypeDescriptionBooleanThe method returns TRUE if this operation is permitted; otherwise it returns FALSE.
user');
const insertedRecordId = record.insert();
if (insertedRecordId == 0) {
  ss.info(record.getErrors());
}
// Info: ["The \"\"First Name\" [first_name]\" field is mandatory. (record id: )",...


getLabel(property) 
Anchor
getLabel()
getLabel()


This method gets the field title.

Info

 The getLabel() method cannot be used with REM attributes. Instead, use the getTitle() method.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN

Example:

Code Block
languagejs
themeEclipse
titlecanCreate
linenumberstrue
current.canCreate()

canDelete()

This method determines if the Access Control Rules permit deleting records in this table.


Return:

TypeDescription
Boolean
StringThe
method returns TRUE if this operation is permitted; otherwise it returns FALSE
field name.


Example:

Code Block
languagejs
themeEclipse
titlecanDeletegetLabel
linenumberstrue
const current = ss.getUser();
const fieldLabel = current.canDelete()

canRead()

This method determines if the Access Control Rules permit reading records in this table.

Return:

TypeDescriptionBooleanThe method returns TRUE if this operation is permitted; otherwise it returns FALSE.
.getLabel('username');
ss.addErrorMessage('Field "' +  fieldLabel + '" cannot be blank');
// Field "Login" cannot be blank

getReModelId() 
Anchor
getremodelid
getremodelid


This method retrieves the ID of the RE model related to the current record. To set a new model ID use the setReModelId method

Example:

Code Block
languagejs
themeEclipse
titlecanRead
linenumberstrue
current.canRead()

canUpdate()

This method determines if the Access Control Rules permit updating records in this table.

Return:

TypeDescription
Boolean

String

The method returns
TRUE if this operation is permitted; otherwise it returns FALSE
the ID of the model. If model is not found, the method returns null.

Example:

Code Block
languagejs
themeEclipse
titlecanUpdategetReModelId
linenumberstrue
current.canUpdate()

deleteMultiple()

This method allows deleting multiple records that meet the query condition. It does not allow deleting attachments.

Do not use it on tables with dependencies. Always delete each record individually.

Also, do not use it combined with the setLimit() method when working with large tables.

Do not use the deleteMultiple() method on the tables with the currency fields. Always delete each record individually. Also, do not use this method with the chooseWindow() or setLimit() methods when working with large tables.

(function executeRule(current, previous = null /*not null only when action is update*/) {
    if (current.getReModelId()) {
        const model = new SimpleRecord('sys_rmc_model');
        model.get(current.getReModelId()); // current model
        current.$$service = model.getValue('cmdb_service_id'); // pass service if field exists
    }
})(current, previous);


getRowCount()


This method gets the amount of items in a row.


Returns

Return

:

TypeDescription
BooleanThis method returns TRUE  if deleted successfully; otherwise returns false
IntegerItems amount in a row specified.

Example:

Code Block
languagejs
themeEclipse
titledeleteMultiplegetRowCount
linenumberstrue
const recordtask = new SimpleRecord('sys_translationtask');
record.addQuery('value', 'like', 'network');
recordtask.query();
ss.info(recordaddInfoMessage('All Tasks Count: ' + task.getRowCount());
// record.deleteMultiple();
deleteRecord(recordId
 All Tasks Count: 2


getTableName()


This method

deletes

gets the current

record.

table name.


Parameter(s):

NameTypeMandatoryDefault ValuerecordIdIntegerN-1

Return:

TypeDescription
BooleanThis method returns TRUE if the record is deleted successfully; otherwise it returns FALSE
StringThe current table name.


Example:

Code Block
languagejs
themeEclipse
titledeleteRecordgetTableName
linenumberstrue
const incidentcurrent = new SimpleRecord('itsm_incident'ss.getUser();
incident.get('155931135900000000');
incident.deleteRecord();

get(propertyOrValue, value)

This method loads an object from a database based on the field value, or, in a specific case, by the sys_id.

ss.info('/list/' + current.getTableName() + '/' + current.sys_id);
// Info: /list/user/155931135900000001

getTitle(attribute) 
Anchor
getTitle()
getTitle()


This method returns the title of the defined RE attribute.

ParameterParameter(s):

NameTypeMandatoryDefault Value
propertyOrValue
columnString
value of record ID or property name. If equals to property name, second param 'value' is mandatory.
Y
NvalueString
N
NULL

Return:

TypeDescription
SimpleRecord object
StringThis method returns the
SimpleRecord object from the table specified in the query
title of the attribute.


Example:

Code Block
languagejs
themeEclipse
titlegetgetTitle
linenumberstrue
const current service= new SimpleRecord('task');
current.get('c_service');
service.get(current.getValue('service'163638951512716126');
if (current.sys_id) {
    ss.info(current.rem_attr.getTitle('reviewed'));
if (!!service.sys_id) {
  const company = new SimpleRecord('org_company');
  company.get('link', service.customer_url);
  ss.eventQueue('notify.company.responsible', current);
}

getAttributes()

This method returns an object with current record properties as keys and properties values as key values.

}
// Info: Review completed


Info

To return column titles which are not part of REM, use the getLabel() method.

getValue(property) 
Anchor
getValue()
getValue()


This method returns the value of the object property based on its name.

If the field is of the Reference or List types, then its sys_id value returns.

Note

To speed up the script execution, use this method to get values of the fields of the Reference type instead of Dot-walking.

As an example, it is preferable to use the current.getValue('reference_field') structure instead of current.reference_field.sys_id one.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN


Return:

TypeDescription
Object
Mixed

The

array containing attributes

string value of the object property.


Code Block
languagejs
themeEclipse
titlegetAttributesgetValue
linenumberstrue
if (!!table.name) {
  const recordconst current = ss.getUser();
const user = new SimpleRecord(table.name'user');
  recorduser.get(recordID);
  if (record.getAttributes()['display_name'] != undefined) {
    current.display_name = `Approval for ${record.display_name}`;
  } else {
    ss.error(`Field display_name in record ${recordID} of table ${table.name} not found. Display Name for approval did not created!`);
  }
}

getClassDisplayValue()

addQuery('timezone_id', current.getValue('timezone_id'));
user.selectAttributes('sys_id');
user.query();
ss.info(user.getRowCount() + ' users have the same timezone as you');
// Info: 24 users have the same timezone as you

hasAttachment()


This method checks whether the record specified has an attachment or notThis method returns the table title. If the title is not set, then returns name.


Return:

TypeDescription
StringTitle or name
BooleanMethod returns 'true' if the record has an attachment; otherwise, it returns 'false'.


Example:

Code Block
languagejs
themeEclipse
titlegetClassDisplayValue
linenumberstrue
email.setSubject(`New ${current.getClassDisplayValue()} has been created`);

getConditionQuery()

This method returns current query condition
languagejs
themeEclipse
titlehasAttachment
linenumberstrue
const current = new SimpleRecord('task');
current.get('163663310116371174');
const hasAttach = current.hasAttachment();
if (!hasAttach) {
  ss.addErrorMessage('File should be attached');
  return;
}
current.state = '2'; // Open
current.update();


initialize()


This method populates all active empty fields with their predefined default values.

It works only for new records that were never saved and cannot be called repeatedly.

This method is called automatically and implicitly at the first set operation (also known as "the setter").


Return:

TypeDescription
StringThe query condition
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titlegetConditionQueryinitialize
linenumberstrue
const task = new SimpleRecord('task');
const conditiontaskRecord = new task.addQuerySimpleRecord('state', '7task');
conditionss.addOrCondition('priority', '<', '3');
condition.addEncodedQuery('active=1');
task.selectAttributes('sys_id');
task.nextinfo(taskRecord.getAttributes().caller);
taskRecord.initialize();
ss.info(tasktaskRecord.getConditionQuerygetAttributes().caller); 
// Info: ((state=7)^OR(priority<3))^(active=1)
ss.info(task.getRowCount());
getDisplayValue(property

// Info: 155931135900000001

insert()


This method returns displayed field or record value (the display_by_ref field). For example, for the reference field the entity name will be returned, but not the ID.

Parameter(s):

uses the field values of the current record to insert a new one.


If the record is not inserted then method returns '0' (zero) and adds an informative error message which can be obtained with getErrors() method.


NameTypeMandatoryDefault ValuePropertyStringNNULL

Return:

TypeDescription
String
A field or record value
  • If record was not inserted, then method returns '0' and you can get a message containing list of errors.
  • As a normal case, a unique ID of the inserted record returns.


Example:

Code Block
languagejs
themeEclipse
titlegetDisplayValueinsert
linenumberstrue
email.setBody(`Dear ${current.getDisplayValue('caller').match(/^(\w+)/g)}:

Your ${current.getClassDisplayValue()} - ${current.number} has been registered`);

getErrors()

If the record creating, updating or deleting will fail, then this method will display error message.
const newTask = new SimpleRecord('task');
newTask.subject = 'Subtask';
const inserterTaskID = newTask.insert();
ss.info(`/record/task/${inserterTaskID}`);
// Info: /record/task/163675231910113745

isTableVcsEnabled()


This method checks whether the VCS enabled attribute is enabled against the specified table or not. 


Return:

TypeDescription
ArrayThe error value
BooleanThis method returns the value of the is_vcs_enabled attribute of record table.

Example:

Code Block
languagejs
themeEclipse
titlegetErrors
linenumberstrue
const table = new SimpleRecord('sys_db_table');
table.get('name', 'task');
if (!table.deleteRecord()) {
  const errors = table.getErrors();
  errors.forEach(error => {
    ss.addErrorMessage(error);
  });
}

getLabel(property)

This method returns the field title.

Eclipse
titleisTableVcsEnabled
linenumberstrue
const current = new SimpleRecord('user');
ss.info(current.isTableVcsEnabled());
// Info: false


matchesCondition(condition)


This method checks whether the current record meets the condition in the current state.Parameter(s):


NameTypeMandatoryDefault Value
property
conditionString
Y
N
N
''


Return:

TypeDescription
StringThe field title.

Example:

BooleanThis method returns 'true' if the record meets the condition specified; otherwise; it returns 'false'.


Code Block
languagejs
themeEclipse
titlegetLabelmatchesCondition
linenumberstrue
const incidenttask = new SimpleRecord('itsm_incidenttask');
task.description = 'emaio';
incident.get('150000000000000001')ss.info(task.matchesCondition('descriptionLIKEemail')); // false
task.description = 'email';
ss.info(incidenttask.getLabelmatchesCondition('callerdescriptionLIKEemail')); // true
getRowCount

next()


This

method gets an amount of the items in a row.

method returns the next record in the query. If this is the first call, this method returns the first record in query. If the query is empty, this method returns 'false'.


Return:

Type
Record or Boolean

Returns:

TypeDescriptionIntegerItems amount in a row specified.


Example:

Code Block
languagejs
themeEclipse
titlegetRowCountnext
linenumberstrue
const incidentuser = new SimpleRecord('itsm_incident'('user');
user.setLimit(1);
user.query();
incidentuser.querynext();
ss.addInfoMessage('Total incident count: ' + incident.getRowCount());

getTableName()

This method returns the current table name.

Return:

TypeDescriptionStringThe current table name.
info(user.sys_id);
// Info: 100000000000000000


Note

Until the method is called, the values of a SimpleRecord object are not available, and the 'Current record is not set' message will occur. Consider the example

ExamplegetTableName

:

Code Block
languagejs
themeEclipse
title
linenumberstrue
const 
incident
task = new SimpleRecord('
itsm_incident'
task');
task.setLimit(1);
task.query();
// task.next();
ss.info(
incident
task.
getTableName()
number);

//
itsm_incident

getValue(property)

This method returns the value of the object property based on its name.

If the field is of the Reference or List types, then its sys_id value returns
 Error: Current record is not set.



orderBy(column)


This method sorts records in the ascending order.


Tip

Call this method several times to order by multiple columns.


Parameter(s):

NameTypeMandatoryDefault Value
Property
columnStringYN


Return:

TypeDescription
MixedThe string value of the object property.
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titlegetValueorderBy
linenumberstrue
const task = new SimpleRecord('task');
task.get('150000000000000001');
ss.info(task.getValue('assigned_user')); // 150000000534521234

hasAttachment()

This method checks whether the record specified has an attachment or not.
 firstLog = new SimpleRecord('sys_log');
firstLog.orderBy('sys_created_at'); // oldest record first
firstLog.addQuery('message', 'like', 'Connection');
firstLog.setLimit(1);
firstLog.selectAttributes(['message', 'sys_created_at']);
firstLog.query();
firstLog.next();
ss.info(firstLog.sys_created_at + ' - ' + firstLog.message);
// Info: 2021-06-03 06:34:02 - IMAP IMAP (Default): Connection error: ...


orderByDesc(column)


This method sorts the records in the descending order.


Parameter(s):

NameTypeMandatoryDefault Value
columnStringYN


Return:

TypeDescription
BooleanMethod returns TRUE if the record has an attachment; otherwise, it returns FALSE
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titlehasAttachmentorderByDesc
linenumberstrue
const tasklastComment = new SimpleRecord('task');
task.get('157531598110402540' SimpleRecord('sys_activities_stream_field');
lastComment.orderByDesc('sys_created_at'); // newest record first
lastComment.setLimit(1);
lastComment.selectAttributes(['value', 'sys_created_by']);
lastComment.query();
lastComment.next();
ss.info(task.hasAttachment()); // false

initialize()

This method populates all active empty fields with their predefined default values.

It works only for new records that were never saved and cannot be called repeatedly.

This method is called automatically and implicitly at the first set operation (also known as "the setter")
lastComment.sys_created_by.display_name + ': ' + lastComment.value);
// Info: John Doe: test

query()


This method applies query to the database selection. After this, it fills in the record set.

Return:

TypeDescription
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titleinitializequery
linenumberstrue
const taskRecordtasks = new SimpleRecord('task');
sstasks.info(Object.entries(taskRecord.getAttributes()).filter(item => !item.includes('')));
taskRecord.initialize();
ss.info(Object.entries(taskRecord.getAttributes()).filter(item => !item.includes('')));

insert()

This method inserts a new record using the field values set for the current record.

If the record is not inserted then method returns '0' (zero) and adds an informative error message which can be obtained with getErrors() method.

Return:

TypeDescriptionInteger
  • If validation errors occurred and record was not updated, then method returns '0' and you can get a message containing list of errors.
  • As a normal case, a unique ID of the inserted record returns.
addQuery('sys_created_at', '>', '2020-01-01');
tasks.orderBy('sys_created_at');
tasks.setLimit(2);
tasks.query();
while (tasks.next()) {
  ss.info('Task number: ' +  tasks.number);
}
// Info: Task number: TSK0000001
// Info: Task number: TSK0000003


selectAttributes(attributes)


This method is intended to optimize database queries. Sometimes, it is necessary to obtain only several object fields, not the whole object. Therefore, this method was added.


Warning

Do not use this method to select records that could be updated or deleted after selecting. Otherwise, some of the record field values may be lost when these records are updated or deleted. Or the action performed may throw an exception looking like this (the example text is given below):

Info

You cannot update the record with the set of shortened attributes. Remove the selectAttributes method call and update again.



NameTypeMandatoryDefault Value
attributesString or ArrayYN


Info

It makes sense to pass a single attribute name as a string. But if you need to pass more than one attribute names, please use Array type (as shown in code example below).

Example:

Code Block
languagejs
themeEclipse
titleinsert
linenumberstrue
const incident = new SimpleRecord('itsm_incident');
incident.insert();

isTableVcsEnabled()

This method checks whether the VCS enabled attribute is enabled against the table specified or not. 

Return:

TypeDescriptionBooleanMethod returns value of is_vcs_enabled property of record table.

Example:

Code Block
languagejs
themeEclipse
titleisTableVcsEnabled
linenumberstrue
const table = new SimpleRecord('sys_db_table');
ss.info(table.isTableVcsEnabled()); // true

matchesCondition(condition)

This method checks whether the current record meets the condition being in the current state.

NameTypeMandatoryDefault ValueconditionStringN''


Return:

TypeDescription
Void
SimpleRecord object

This method

does not return a value.

returns a SimpleRecord object containing attributes and values.

Note

Regardless of the initial attribute set content, the returned object always contains the sys_id attribute. See code examples below for more clarity.


Example:

Code Block
languagejs
themeEclipse
titleselectAttributes (String)matchesCondition
linenumberstrue
const taskrecord = new SimpleRecord('taskuser');
rec.description = 'dsc';
ss.info(rec.matchesCondition('descriptionLIKEesc')); // false
rec.description = 'desc';
ss.info(rec.matchesCondition('descriptionLIKEesc')); // true

next()

If this is a new request, then this method returns the first record from the list; otherwise it returns FALSE, in the case if the record is unavailable.

Return:

TypeRecord or Boolean
record.selectAttributes('email');
record.query();
record.next();
ss.info(record.getAttributes());
// Info: {"email":"john.doe@email.com","sys_id":"162423321917274937"}


Example:

Code Block
languagejs
themeEclipse
titlenextselectAttributes (Array)
linenumberstrue
const incidentrecord = new SimpleRecord('itsm_incidentuser');
incidentrecord.selectAttributes('sys_id'['email', 'username']);
record.query();
incidentrecord.querynext();
while (incident.nextss.info(record.getAttributes()){;
//  ss.info(incident.sys_id);
}

orderBy(column)

This method sorts records in the ascending order.

Info: {"email":"john.doe@email.com","username":"john.doe","sys_id":"162423321917274937"}

setAbortAction(flag)


This method is used in business rules and sets a flag, indicating that the current operation (insert/update/delete) will be interrupted.


Note

Please note that the code will not be executed if it is typed after calling this method in the script body.


Note

It is not recommended to use thismethod with async business rules. It may cause unpredictable system behavior

Tip

Call this method several times to order by multiple columns.


Parameter(s):

NameTypeMandatoryDefault Value
column
flag
String
BooleanYN


Return:

TypeDescription
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titleorderBy
linenumberstrue
const incident = new SimpleRecord('itsm_incident');
incident.orderBy('sys_created_at');
incident.query();

orderByDesc(column)

setAbortAction
linenumberstrue
const current = new SimpleRecord('task');
current.get('163663310116371174');
const hasAttach = current.hasAttachment();
if (!hasAttach) {
    ss.addErrorMessage('File should be attached!');
    current.setAbortAction(true);
}
current.state = '2'; // Open
current.update();

setLimit(maxNumRecords)


This method limits the number of records selected by SimpleRecord query methodsThis method sorts the records in the descending order.


Parameter(s):

NameTypeMandatoryDefault Value
column
maxNumRecords
String
IntegerYN


Return:

TypeDescription
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titleorderByDescsetLimit
linenumberstrue
const incidentrecord = new SimpleRecord('itsm_incident');
incident.orderByDesc('sys_updated_atuser');
incident.query();

query()

This method runs a query against the selection from the database, based on the $this→query. After this, it fills in the
record
set.

Return:

TypeDescriptionVoidThis method does not return a value.

selectAttributes(attributes)

This method is intended to optimize database queries. Sometimes, it is necessary to obtain only several object fields, not the whole object, Therefore, this method was added.

Warning

Do not use this method when selecting records that can be updated after being selected. Otherwise, when updating, some of the record field values may be lost, or record updating will throw an exception looking like this:

.setLimit(3);
record.query();
ss.info(record.getRowCount());
// Info: 3


setMultipleValue(property,value)


This method sets the properties values for every entry in the current selection.


Parameter(s):

InfoYou can't save incomplete record.

NameTypeMandatoryDefault Value
attributes
propertyStringYN
valueString
or Array
YN

Return:

TypeDescription
SimpleRecord object
Void

This method

returns a SimpleRecord object containing attributes.
Example:

does not return a value.


Code Block
languagejs
themeEclipse
titleselectAttributes (String or Array)setMultipleValue
linenumberstrue
const recordtask = new SimpleRecord('usertask');
recordtask.selectAttributesaddQuery('emailstate', '7'); // Draft
recordtask.query();
while (record.nextss.info(task.getRowCount()) {
  ss.info(record.email || 'null;
task.setMultipleValue('state', '2'); // not null
  ss.info(record.first_name || 'null'); // null
  ss.info(record.username || 'null'); // null
  // other fields are null
}// Open
// task.updateMultiple();

setReModelId(reModelId) 
Anchor
setremodelid
setremodelid


This method sets the ID of the defined RE model. To get the model ID, use the getReModelId method.

Parameter(s):

NameTypeMandatoryDefault Value
reModelIdStringYN

If the reModelId parameter is equal to 'null', the REM, related to the record, will be detached. 

Return:

TypeDescription
Void

This method does not return a value.

Example:

Code Block
languagejs
themeEclipse
titleselectAttributes (Array)getReModelId
linenumberstrue
const recordtask = new SimpleRecord('user');
record.selectAttributes(['email', 'first_name']);
record.query();
while (record.next()) {
  ss.info(record.email || 'null'); // not null
  ss.info(record.first_name || 'null'); // not null
  ss.info(record.username || 'null SimpleRecord('task');
task.get('163352033916904699');
if (task.getValue('service') === '164069027812962298') { // Email Server Service
    task.setReModelId('158569205818704980'); // null
  // other fields are null
}

setAbortAction(flag)

This method sets a flag, indicating that will be current operation (insert/update/delete) interrupted. It used in business rules.

Parameter(s):

NameTypeMandatoryDefault ValueflagBooleanYN

Return:

TypeDescription
 Email Server Access Request
} else {
    task.setReModelId(null);
}
task.update();


Note

When calling the method on a SimpleRecord() instance, the values of its attributes bound to the previous model will be reset.

After calling the method and updating the сurrent record, the attribute values bound to the previous model will be lost

VoidThis method does not return a value

.

Example:

Code Block
languagejs
themeEclipse
titlesetAbortActionsetReModelId
linenumberstrue
const now = new SimpleDateTime(); // now

if (now.before(new SimpleDateTime(current.appropriate_date))) {
  current.setAbortAction(true);
  ss.addErrorMessage(`Can't be updated before ${new SimpleDateTime(current.appropriate_date)}.getDisplayValue()`);
}

setLimit(maxNumRecords)

Sets a limit for a number of records are fetched by SimpleRecord query.

Parameter(s):

NameTypeMandatoryDefault ValuemaxNumRecordsIntegerYN

Return:

TypeDescriptionVoidThis method does not return a value.

Example:

Code Block
languagejs
themeEclipse
titlesetLimit
linenumberstrue
const incident = new SimpleRecord('itsm_incident');
incident.orderByDesc('sys_created_at');
incident.setLimit(1);
incident.query(); // last created incident
if (incident.getRowCount() > 0) {
  incident.next();
  ss.info(`Last incident was created at ${incident.sys_created_at}`);
}

setMultipleValue(property,value)

This method sets the properties values for every entry in the current selection.

Parameter(s):

NameTypeMandatoryDefault ValuepropertyStringYNvalueStringYN

Return:

TypeDescriptionVoid

This method does not return a value.

(function executeRule(current, previous = null /*not null only when action is update*/ ) {
    // before rule triggered by service change

    ss.importIncludeScript('getRemAttributes');
    const rmc = new SimpleRecord('sys_rmc_model');
    rmc.addQuery('cmdb_service_id', current.getValue('service'));
    rmc.addQuery('active', true);
    rmc.selectAttributes('sys_id');
    rmc.setLimit(1);
    rmc.query();
    if (rmc.next()) {
        const previousModelAttributes = getRemAttributes(current);
        current.setReModelId(rmc.sys_id);
        const currentModelAttributes = getRemAttributes(current);

        Object.keys(previousModelAttributes).forEach(attributeName => {
            if (currentModelAttributes.hasOwnProperty(attributeName)) {
                current.rem_attr[attributeName] = previousModelAttributes[attributeName];
            }
        })
    } else {
        current.setReModelId(null);
    }

})(current, previous);

setValue(property, value) 
Anchor
setValue()
setValue(

Code Block
languagejs
themeEclipse
titlesetMultipleValue
linenumberstrue
const task = new SimpleRecord('task');
task.addQuery('state', '7'); // Draft
task.query();
task.setMultipleValue('state', '2'); Open
task.updateMultiple();
setValue(property, value

)


This method sets the value of the field in the current record.

Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN
valueStringYN


Return:

TypeDescription
VoidThis property does not return a value.


Example:

Code Block
languagejs
themeEclipse
titlesetValue
linenumberstrue
const task = new SimpleRecord('task');
task.setValue('subject', 'mail');
task.insert();


silentMode(enable)


This method is intended to update the record without executing any entities related to this record implementing the business logic, such as business rules, notifications, workflows, etc.


NameTypeMandatoryDefault Value
enableBooleanYNNtrue


TypeDescription
VoidThis property does not return a value.


Code Block
languagejs
themeEclipse
titlesilentMode
linenumberstrue
const task = new SimpleRecord('task');
task.addQuery('active', false);
task.addQuery('approval_state', 'isemptyconst task = new SimpleRecord('task');
task.query();
ss.info(task.nextgetRowCount());
task.silentMode();
task.setMultipleValue('approval_state', 'not_requested'); // set Default Value
//task.updateupdateMultiple();

update()


This method updates a database record. database record.

Info

This method is used for existing records.

  • If the record existed before, the changes are applied.
  • If the record
does
  • did not exist
, it is inserted.
  • before, the getErrors() method will return this error: "Unable to update new record. Use `insert()` instead. (record id: )"


Return:

TypeDescription
IntegerString
  • If validation errors occurred and record was not updated, then method returns '0' and you can get a message containing list of errors;
  • As a normal case, an ID of the updated (inserted) record returns.


Example:

Code Block
languagejs
themeEclipse
titleupdate
linenumberstrue
const incidentcurrent = new SimpleRecord('itsm_incidentuser');
incidentcurrent.get(record_id);
if (incident.sys_id) {
  incident.subject += " (repair)";
  const updatedID = incidentss.getUserId());
current.timezone_id = '156076775207670452'; // UTC
ss.info(current.update();
  if (updatedID == 0) {
    ss.debug(incident);
ss.info(current.getErrors());
// Info: }
}155931135900000001
// Info: []


updateMultiple()


This method updates all the selection entries.

Return:

TypeDescription
Void or Integer
  • If validation errors occurred and record was not updated, then method returns '0' and you can get a message containing list of errors;
  • As a normal caseNormally, this method does not returns return a value.


Code Block
languagejs
themeEclipse
titleupdateMultiple
linenumberstrue
const task = new SimpleRecord('task');
task.addQuery('state', '0'); // Open
task.query();
ss.info(task.getRowCount());
task.setMultipleValue('state', '10'); // Canceled
// task.updateMultiple();


Table of Contents
absoluteUrltrue
printablefalse