You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Этот серверный класс представляет собой методы для работы с записями базы данных.

SimpleRecord(tableName)


Этот метод создает объект класса SimpleRecord для конкретной таблицы.


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
tableNameStringДаНет

Пример:

SimpleRecord
const taskRecord = new SimpleRecord('task');


REM attribute object


В классе SimpleRecord имеется отдельный объект Record Extended Modelsrem_attr, который содержит информацию о REM attributes. Используйте его для чтения и редактирования значений атрибута REM текущей записи с помощью других методов класса, как в примере ниже.

rem_attr имеет несколько методов аналогичных методам SimpleRecord: 

Например:

record.rem_attr.getValue('my_rem_attribute');

Параметр:

NameTypeОбязательныйЗначение по умолчанию
propertyStringДаНет

Возвращаемое значение::

ТипОписание
SimpleRecord objectМетод возвращает значение SimpleRecord object из определенной модели расширенной записи. Метод возвращает "null", если запись не имеет модели расширенной раписи.

Пример:

get using REM
const record = new SimpleRecord('task');
record.get('160638931615274614');
if (record.getReModelId()) {
    ss.info(record.rem_attr.description);
}

addOrCondition(property, operator, value)


Этот метод добавляет параметр 2 или 3, или условие к существующему запросу. Он работает в сочетании с любым из методов addQuery(). В этом методе вы можете использовать любой предпочитаемый оператор из списка операторов условий, указанный либо в нижнем, либо в верхнем регистре. Обратите внимание, что необходимо использовать системное имя оператора в скриптах.


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
propertyStringДаНет
operatorString (больше информации в статье Операторы условий)НетНет
valueInteger / String / Boolean / ArrayДаНет


Возвращаемое значение::

ТипОписание
SimpleRecordЗапрос содержащий объект SimpleRecord или условие, добавленное к этому объекту


Пример:

addOrCondition
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();
// Инфо: Условие запроса: (subjectLIKEnot work)^OR(descriptionLIKEnot work)

addQuery(property, operator, value)


Используйте этот метод, чтобы добавить условие для выбора записей из базы данных. В этом методе позволяет использовать любой предпочитаемый оператор из списка Операторы условия, указанный либо в нижнем, либо в верхнем регистре. Обратите внимание, необходимо использовать системное имя оператора в скриптах.


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
propertyStringДаНет
operatorString (refer to the Condition Operators article for more information)НетНет
valueInteger / String / Boolean / ArrayДаНет


Возвращаемое значение::

ТипОписание
SimpleRecordУсловие запроса добавленое в объект SimpleRecord.


Пример:

addQuery
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

addEncodedQuery(condition)


Используйте данный метод, чтобы добавить закодированный запрос и применить его к текущему методу запроса.

Допустимо использование декодированного запроса.


Параметр:

НазваниеТипОбязательныйЗначение по умолчанию
conditionString ДаНет

Возвращаемое значение::

ТипОписание
VoidМетод не возвращает значение.

Пример:

addEncodedQuery
const currentUser = ss.getUser();
const reciever = new SimpleRecord('employee');
reciever.addQuery('active', true);
if (currentUser.company.class === 'internal') {
    reciever.addEncodedQuery(`(company=${currentUser.getValue('company')})`);
} else {
    reciever.addEncodedQuery(`%28sys_db_table_id%3D158645243815904649%5Esys_created_byDYNAMIC156957117519820256%29`);
}
ss.info('Decoded condition: ' + reciever.getConditionQuery());
reciever.query();
// Инфо: Декодированное условие: (active=1)^((sys_db_table_id=158645243815904649^sys_created_byDYNAMIC156957117519820256))

canCreate()


Используйте этот метод, чтобы проверить, удовлетворяет ли добавление новых записей в указанную таблицу правилу управления доступом (ACL).

Так же используйте этот метод в  UI Actions, чтобы оптимизировать видимость записей.


Возвращаемое значение::

ТипОписание
BooleanМетод возвращает значение "true", если действие разрешено, если нет, метод возвращает "false".


Пример:

canCreate
current.canCreate();

canDelete()


Используйте этот метод, чтобы проверить, удовлетворяет ли удаление записей из указанной таблицы правилу управления доступом (ACL).

Так же используйте этот метод в  UI Actions, чтобы оптимизировать видимость записей.


Возвращаемое значение:

ТипОписание
BooleanМетод возвращает значение "true", если действие разрешено, если нет, метод возвращает "false".


Пример:

canDelete
current.canDelete();

canRead()


Используйте этот метод, чтобы проверить, удовлетворяет ли чтение записей в указанной таблице правилу управления доступом (ACL).

Так же используйте этот метод в  UI Actions, чтобы оптимизировать видимость записей.


Возвращаемое значение::

ТипОписание
BooleanМетод возвращает значение "true", если действие разрешено, если нет, метод возвращает "false".


Пример:

canRead
current.canRead();

canUpdate()


Используйте этот метод, чтобы проверить, удовлетворяет ли обновление записей в указанной таблице правилу управления доступом (ACL).

Так же используйте этот метод в  UI Actions, чтобы оптимизировать видимость записей.


Возвращаемое значение::

ТипОписание
BooleanМетод возвращает значение "true", если действие разрешено, если нет, метод возвращает "false".


Пример:

canUpdate
current.canUpdate();

deleteMultiple()


Используйте этот метод, чтобыудалить несколько записей в выборке запроса. Обратите внимание, что вложения не могут быть удалены с помощью этого метода.

Не используйте этот метод для таблиц с зависимостями. Всегда удаляйте каждую запись по отдельности.


Возвращаемое значение::

ТипОписание
BooleanМетод возвращает "true", если записи успешно удалены, в случае ошибки метод возвращает значение "false".


Пример:

deleteMultiple
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()


Используйте этот метод для удаления текущей записи.


Возвращаемое значение:

ТипОписание
BooleanМетод возвращает значение "true", если запись успешно удалена, в случае ошибки метод возвращает значение "false".


Пример:

deleteRecord
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)


Используйте этот метод, чтобы загружить объект из базы данных по значению поля или, в некоторых случаях, по  sys_id.


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
propertyOrValue

Значение строки ID записи или имени свойства. Если значение равно имени свойства, второй параметр value является обязательным.

Передача значения 'NULL' или пустой строки в качестве значения параметра propertyOrValue ведет к исключению:

"Аргумент 1 переданный в "get()" не может быть пустым".

ДаНет
valueStringНетNULL


Возвращаемое значение:

ТипОписание
SimpleRecord objectЭтот метод возвращает объект SimpleRecord из таблицы, указанной в запросе.


Пример:

get
const current = new SimpleRecord('task');
current.get('163663310116371174');

if (current.sys_id) {
    const company = new SimpleRecord('org_company');
    company.get('c_website', current.c_customer_url);
    ss.eventQueue('notify.responsible', current, company.responsible.email);
}


getAttributes()


Данный метод возвращает объект со свойствами текущей записи в качестве ключей и значения свойств как значения ключей.

Возвращаемое значение:

ТипОписание
ObjectМассив атрибутов

Пример:

getAttributes
const userRecord = ss.getUser();
ss.info(userRecord.getAttributes());
// Инфо: {"sys_id":"155931135900000001","sys_created_at":"2019-09-30 00:00:00","sys_updated_at":"2021-06-28...

getClassDisplayValue()


Данный метод возвращает заголовок таблицы. Если он не установлен, то метод возвразает системное имя таблицы.


Возвращаемое значение:

ТипОписание
StringЗаголовок или название


Пример:

getClassDisplayValue
const current = new SimpleRecord('task');
current.get('163663310116371174');
ss.info(current.getClassDisplayValue());
// Инфо: Задача

getConditionQuery()


Метод возвращает текущее условие запроса.

Возвращаемое значение:

ТипОписание
StringУсловие запроса

Пример:

getConditionQuery
const task = new SimpleRecord('task');
const condition = task.addQuery('state', '7');
condition.addOrCondition('priority', '<', '3');
ss.info('Condition before query: ' + task.getConditionQuery());
task.query();
ss.info('Condition after query: ' + task.getConditionQuery());
// Info: Условие до запроса: (state=7)^OR(priority<3)
// Info: Условие после:

getDisplayValue(property) 


Данный метод возвращает значение поля display_by_ref или значение записи. Например, для поля reference возвращается название сущности, а не ID.


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
PropertyStringНетNULL


Возвращаемое значение:

TypeОписание
StringПоле или значение записи


Пример:

getDisplayValue
const current = new SimpleRecord('task');
current.get('163663310116371174');
ss.info(current.getDisplayValue('caller'));
ss.info(current.getValue('caller'));
// Инфо: Иван Иванов
// Инфо: 155931135900000001

getErrors() 


Этот метод отображает сообщение об ошибке в случае сбоя при создании, обновлении или удалении записи.

Используйте этот метод в целях контроля, если в ваших скриптах есть какие-либо ошибки проверки.

Настоятельно рекоментдуется использовать данный метод, так как некоторые ошибки проверки могут не отображаться в процессе отладки.

Например, ошибки в запросах условия, переданных методом addEncodedQuery(condition) или аналогичным, можно отобразить, вызвав этот метод.

Возвращаемое значение:

ТипОписание
ArrayЗначение ошибки

Пример:

getErrors
const record = new SimpleRecord('user');
const insertedRecordId = record.insert();
if (insertedRecordId == 0) {
  ss.info(record.getErrors());
}
// Инфо: ["Поле \"\"First Name\" [first_name]\" является обязательным. (record id: )",...

getLabel(property) 


Используйте этот метод, чтобы получить заголовок поля.

Метод getLabel() не используется с атрибутами REM. Вместо этого используйте метод getTitle().


Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
propertyStringДаНет


Возвращаемое значение:

ТипОписание
StringНазвание поля


Пример:

getLabel
const current = ss.getUser();
const fieldLabel = current.getLabel('username');
ss.addErrorMessage('Поле "' +  fieldLabel + '" должно быть заполнено');
// Поле "Логин"должно быть заполнено

getReModelId() 


Используйте этот метод, чтобы извлечь ID расширенной модели записи, относящейся к текущей записи. Используйте метод setReModelId, чтобы установить новый ID модели .

Возвращаемое значение:

ТипОписание

String

Метод возвращает ID модели. Если модель не найдена, метод возвращает значение 'null'.

Пример:

getReModelId
(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'); // передает в сервис, если поле существует
    }
})(current, previous);


getRowCount()


Используйте этот метод, чтобы получить количество элементов в ряду.

Возвращаемое значение:

ТипОписание
IntegerКоличество элементов в ряду

Пример:

getRowCount
const task = new SimpleRecord('task');
task.query();
ss.addInfoMessage('Количество всех задач: ' + task.getRowCount());
//Количество всех задач: 2

getTableName()


Используйте этот метод, чтобы получить системное название текущей страницы.


Возвращаемое значение:

ТипОписание
StringСистемное название текущей таблицы


Пример:

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

getTitle(attribute) 


Метод возвращает заголовок, определенный атрибутом расширенной модели записи.

Параметр:

НазваниеТипОбязательныйЗначение по умолчанию
columnStringДаНет

Возвращаемое значение:

ТипОписание
StringМетод возвращает заголовок атрибута.


Пример:

getTitle
const current = new SimpleRecord('task');
current.get('163638951512716126');
if (current.sys_id) {
    ss.info(current.rem_attr.getTitle('reviewed'));
}
// Инфо: Ревью завершено

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

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.

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

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

Параметры:

NameTypeMandatoryЗначение по умолчанию
propertyStringYN


Возвращаемое значение:

TypeDescription
Mixed

The string value of the object property.


getValue
const current = ss.getUser();
const user = new SimpleRecord('user');
user.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 not.


Возвращаемое значение:

TypeDescription
BooleanThe method returns 'true' if the record has an attachment; otherwise, it returns 'false'.

Пример:

hasAttachment
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 have never been saved and cannot be called repeatedly.

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


Возвращаемое значение:

TypeDescription
VoidМетод не возвращает значение.

Пример:

initialize
const taskRecord = new SimpleRecord('task');
ss.info(taskRecord.getAttributes().caller);
taskRecord.initialize();
ss.info(taskRecord.getAttributes().caller);
// Info: 
// Info: 155931135900000001

insert()


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


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


Возвращаемое значение:

TypeDescription
Integer
  • If record was not inserted, the method returns '0' and you can get a message containing a list of errors.
  • If a record was inserted, the method returns a unique ID of the inserted record.


Пример:

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


Возвращаемое значение:

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

Пример:

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


NameTypeMandatoryЗначение по умолчанию
conditionStringN''

Возвращаемое значение:

TypeDescription
BooleanThis method returns 'true' if the record meets the condition specified; otherwise; it returns 'false'.
matchesCondition
const task = new SimpleRecord('task');
task.description = 'emaio';
ss.info(task.matchesCondition('descriptionLIKEemail')); // false
task.description = 'email';
ss.info(task.matchesCondition('descriptionLIKEemail')); // true

next()


This method returns the next record in the query. 


Возвращаемое значение:

TypeDescription
Record or BooleanIf this is the first call, this method returns the first record in the query.
If the query is empty, this method returns 'false'.


Пример:

next
const user = new SimpleRecord('user');
user.setLimit(1);
user.query();
user.next();
ss.info(user.sys_id);
// Info: 100000000000000000

Until the method is called, the values of a SimpleRecord object are not available, and the 'Current record is not set' message appears. See the Пример:

const task = new SimpleRecord('task');
task.setLimit(1);
task.query();
// task.next();
ss.info(task.number);
// Error: Current record is not set.

orderBy(column)


This method sorts the records in the ascending order.

Call this method several times to order by multiple columns.


Параметры:

NameTypeMandatoryЗначение по умолчанию
columnStringYN


Возвращаемое значение:

TypeDescription
VoidМетод не возвращает значение.


Пример:

orderBy
const 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.


Параметры:

NameTypeMandatoryЗначение по умолчанию
columnStringYN


Возвращаемое значение:

TypeDescription
VoidМетод не возвращает значение.


Пример:

orderByDesc
const lastComment = new 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(lastComment.sys_created_by.display_name + ': ' + lastComment.value);
// Info: John Doe: test

query()


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

Возвращаемое значение:

TypeDescription
VoidМетод не возвращает значение.


Пример:

query
const tasks = new SimpleRecord('task');
tasks.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)


Use this method tooptimize the database queries, especially when it is necessary to obtain only several object fields, not the whole object. 

Do not use this method to select records that can be updated or deleted after selecting. Otherwise, some of the record field values may be lost when these records are updated or deleted. The action performed may also throw an exception similar to:

You cannot save an incomplete record.


NameTypeMandatoryЗначение по умолчанию
attributesString or ArrayYN

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


Возвращаемое значение:

TypeDescription
SimpleRecord object

This method returns a SimpleRecord object containing attributes and values.

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

Пример:

selectAttributes (String)
const record = new SimpleRecord('user');
record.selectAttributes('email');
record.query();
record.next();
ss.info(record.getAttributes());
// Info: {"email":"john.doe@email.com","sys_id":"162423321917274937"}


Пример:

selectAttributes (Array)
const record = new SimpleRecord('user');
record.selectAttributes(['email', 'username']);
record.query();
record.next();
ss.info(record.getAttributes());
// Info: {"email":"john.doe@email.com","username":"john.doe","sys_id":"162423321917274937"}

setAbortAction(flag)


Use this method in business rules to set a flag indicating that the current operation (insert/update/delete) is interrupted.


Note that the code is not executed if it is typed after calling this method in the script body.

It is not recommended to use this method with async business rules as it may cause unpredictable system behavior.


Параметры:

NameTypeMandatoryЗначение по умолчанию
flagBooleanYN


Возвращаемое значение:

TypeDescription
VoidМетод не возвращает значение.


Пример:

setAbortAction
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 the SimpleRecord query methods.


Параметры:

NameTypeMandatoryЗначение по умолчанию
maxNumRecordsIntegerYN


Возвращаемое значение:

TypeDescription
VoidМетод не возвращает значение.


Пример:

setLimit
const record = new SimpleRecord('user');
record.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.


Параметры:

NameTypeMandatoryЗначение по умолчанию
propertyStringYN
valueStringYN

Возвращаемое значение:

TypeDescription
Void

Метод не возвращает значение.

setMultipleValue
const task = new SimpleRecord('task');
task.addQuery('state', '7'); // Draft
task.query();
ss.info(task.getRowCount());
task.setMultipleValue('state', '2'); // Open
// task.updateMultiple();

setReModelId(reModelId) 


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

Параметры:

NameTypeMandatoryЗначение по умолчанию
reModelIdStringYN

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

Возвращаемое значение:

TypeDescription
Void

Метод не возвращает значение.

Пример:

getReModelId
const task = new SimpleRecord('task');
task.get('163352033916904699');
if (task.getValue('service') === '164069027812962298') { // Email Server Service
    task.setReModelId('158569205818704980'); // Email Server Access Request
} else {
    task.setReModelId(null);
}
task.update();

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.


setValue(property, value) 


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

Параметры:

NameTypeMandatoryЗначение по умолчанию
propertyStringYN
valueStringYN


Возвращаемое значение:

TypeDescription
VoidThis property does not return a value.


Пример:

setValue
const task = new SimpleRecord('task');
task.setValue('subject', 'mail');
task.insert();

silentMode(enable)


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


NameTypeMandatoryЗначение по умолчанию
enableBooleanNtrue
TypeDescription
VoidThis property does not return a value.
silentMode
const task = new SimpleRecord('task');
task.addQuery('active', false);
task.addQuery('approval_state', 'isempty');
task.query();
ss.info(task.getRowCount());
task.silentMode();
task.setMultipleValue('approval_state', 'not_requested'); // set Default Value
//task.updateMultiple();

update()


This method updates a database record.

This method is used for existing records.

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


Возвращаемое значение:

TypeDescription
Integer
  • If record was not updated, then method returns '0' and you can get a message containing list of errors;
  • The method returns an ID of the updated record if no errors occured.


Пример:

update
const current = new SimpleRecord('user');
current.get(ss.getUserId());
current.timezone_id = '156076775207670452'; // UTC
ss.info(current.update());
ss.info(current.getErrors());
// Info: 155931135900000001
// Info: []

updateMultiple()


This method updates all the selection entries.

Возвращаемое значение:

TypeDescription
Void or Integer
  • If validation errors occurred and the record was not updated, the method returns '0' and a message containing a list of errors;
  • The method does not return a value if no errors occured.
updateMultiple
const task = new SimpleRecord('task');
task.addQuery('state', '0'); // Open
task.query();
ss.info(task.getRowCount());
task.setMultipleValue('state', '10'); // Canceled
// task.updateMultiple();

  • No labels