You are viewing an old version of this page. View the current version.
Compare with Current View Page History
« Previous Version 2 Next »
Этот серверный класс представляет собой методы для работы с записями базы данных.
SimpleRecord(tableName)
Этот метод создает объект класса SimpleRecord для конкретной таблицы.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
tableName | String | Да | Нет |
Пример:
const taskRecord = new SimpleRecord('task');
REM attribute object
В классе SimpleRecord имеется отдельный объект Record Extended Models – rem_attr, который содержит информацию о REM attributes. Используйте его для чтения и редактирования значений атрибута REM текущей записи с помощью других методов класса, как в примере ниже.
rem_attr имеет несколько методов аналогичных методам SimpleRecord:
Например:
record.rem_attr.getValue('my_rem_attribute');
Параметр:
Name | Type | Обязательный | Значение по умолчанию |
---|---|---|---|
property | String | Да | Нет |
Возвращаемое значение::
Тип | Описание |
---|---|
SimpleRecord object | Метод возвращает значение SimpleRecord object из определенной модели расширенной записи. Метод возвращает "null", если запись не имеет модели расширенной записи. |
Пример:
const record = new SimpleRecord('task'); record.get('160638931615274614'); if (record.getReModelId()) { ss.info(record.rem_attr.description); }
addOrCondition(property, operator, value)
Этот метод добавляет параметр 2 или 3, или условие к существующему запросу. Он работает в сочетании с любым из методов addQuery(). В этом методе вы можете использовать любой предпочитаемый оператор из списка операторов условий, указанный либо в нижнем, либо в верхнем регистре. Обратите внимание, что необходимо использовать системное имя оператора в скриптах.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
property | String | Да | Нет |
operator | String (больше информации в статье Операторы условий) | Нет | Нет |
value | Integer / String / Boolean / Array | Да | Нет |
Возвращаемое значение::
Тип | Описание |
---|---|
SimpleRecord | Запрос содержащий объект SimpleRecord или условие, добавленное к этому объекту |
Пример:
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)
Используйте этот метод, чтобы добавить условие для выбора записей из базы данных. В этом методе позволяет использовать любой предпочитаемый оператор из списка Операторы условия, указанный либо в нижнем, либо в верхнем регистре. Обратите внимание, необходимо использовать системное имя оператора в скриптах.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
property | String | Да | Нет |
operator | String (refer to the Condition Operators article for more information) | Нет | Нет |
value | Integer / String / Boolean / Array | Да | Нет |
Возвращаемое значение::
Тип | Описание |
---|---|
SimpleRecord | Условие запроса добавленое в объект SimpleRecord. |
Пример:
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)
Используйте данный метод, чтобы добавить закодированный запрос и применить его к текущему методу запроса.
Допустимо использование декодированного запроса.
Параметр:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
condition | String | Да | Нет |
Возвращаемое значение::
Тип | Описание |
---|---|
Void | Метод не возвращает значение. |
Пример:
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". |
Пример:
current.canCreate();
canDelete()
Используйте этот метод, чтобы проверить, удовлетворяет ли удаление записей из указанной таблицы правилу управления доступом (ACL).
Так же используйте этот метод в UI Actions, чтобы оптимизировать видимость записей.
Возвращаемое значение:
Тип | Описание |
---|---|
Boolean | Метод возвращает значение "true", если действие разрешено, если нет, метод возвращает "false". |
Пример:
current.canDelete();
canRead()
Используйте этот метод, чтобы проверить, удовлетворяет ли чтение записей в указанной таблице правилу управления доступом (ACL).
Так же используйте этот метод в UI Actions, чтобы оптимизировать видимость записей.
Возвращаемое значение::
Тип | Описание |
---|---|
Boolean | Метод возвращает значение "true", если действие разрешено, если нет, метод возвращает "false". |
Пример:
current.canRead();
canUpdate()
Используйте этот метод, чтобы проверить, удовлетворяет ли обновление записей в указанной таблице правилу управления доступом (ACL).
Так же используйте этот метод в UI Actions, чтобы оптимизировать видимость записей.
Возвращаемое значение::
Тип | Описание |
---|---|
Boolean | Метод возвращает значение "true", если действие разрешено, если нет, метод возвращает "false". |
Пример:
current.canUpdate();
deleteMultiple()
Используйте этот метод, чтобыудалить несколько записей в выборке запроса. Обратите внимание, что вложения не могут быть удалены с помощью этого метода.
Не используйте этот метод для таблиц с зависимостями. Всегда удаляйте каждую запись по отдельности.
Возвращаемое значение::
Тип | Описание |
---|---|
Boolean | Метод возвращает "true", если записи успешно удалены, в случае ошибки метод возвращает значение "false". |
Пример:
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". |
Пример:
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()" не может быть пустым". | Да | Нет |
value | String | Нет | NULL |
Возвращаемое значение:
Тип | Описание |
---|---|
SimpleRecord object | Этот метод возвращает объект SimpleRecord из таблицы, указанной в запросе. |
Пример:
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 | Массив атрибутов |
Пример:
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 | Заголовок или название |
Пример:
const current = new SimpleRecord('task'); current.get('163663310116371174'); ss.info(current.getClassDisplayValue()); // Инфо: Задача
getConditionQuery()
Метод возвращает текущее условие запроса.
Возвращаемое значение:
Тип | Описание |
---|---|
String | Условие запроса |
Пример:
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.
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
Property | String | Нет | NULL |
Возвращаемое значение:
Type | Описание |
---|---|
String | Поле или значение записи |
Пример:
const current = new SimpleRecord('task'); current.get('163663310116371174'); ss.info(current.getDisplayValue('caller')); ss.info(current.getValue('caller')); // Инфо: Иван Иванов // Инфо: 155931135900000001
getErrors()
Этот метод отображает сообщение об ошибке в случае сбоя при создании, обновлении или удалении записи.
Используйте этот метод в целях контроля, если в ваших скриптах есть какие-либо ошибки проверки.
Настоятельно рекоментдуется использовать данный метод, так как некоторые ошибки проверки могут не отображаться в процессе отладки.
Например, ошибки в запросах условия, переданных методом addEncodedQuery(condition) или аналогичным, можно отобразить, вызвав этот метод.
Возвращаемое значение:
Тип | Описание |
---|---|
Array | Значение ошибки |
Пример:
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().
Параметры:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
property | String | Да | Нет |
Возвращаемое значение:
Тип | Описание |
---|---|
String | Название поля |
Пример:
const current = ss.getUser(); const fieldLabel = current.getLabel('username'); ss.addErrorMessage('Поле "' + fieldLabel + '" должно быть заполнено'); // Поле "Логин"должно быть заполнено
getReModelId()
Используйте этот метод, чтобы извлечь ID расширенной модели записи, относящейся к текущей записи. Используйте метод setReModelId, чтобы установить новый ID модели .
Возвращаемое значение:
Тип | Описание |
---|---|
String | Метод возвращает ID модели. Если модель не найдена, метод возвращает значение 'null'. |
Пример:
(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 | Количество элементов в ряду |
Пример:
const task = new SimpleRecord('task'); task.query(); ss.addInfoMessage('Количество всех задач: ' + task.getRowCount()); //Количество всех задач: 2
getTableName()
Используйте этот метод, чтобы получить системное название текущей страницы.
Возвращаемое значение:
Тип | Описание |
---|---|
String | Системное название текущей таблицы |
Пример:
const current = ss.getUser(); ss.info('/list/' + current.getTableName() + '/' + current.sys_id); // Info: /list/user/155931135900000001
getTitle(attribute)
Метод возвращает заголовок, определенный атрибутом расширенной модели записи.
Параметр:
Название | Тип | Обязательный | Значение по умолчанию |
---|---|---|---|
column | String | Да | Нет |
Возвращаемое значение:
Тип | Описание |
---|---|
String | Метод возвращает заголовок атрибута. |
Пример:
const current = new SimpleRecord('task'); current.get('163638951512716126'); if (current.sys_id) { ss.info(current.rem_attr.getTitle('reviewed')); } // Инфо: Ревью завершено
Чтобы вернуть колонки, заголовки которых не являются частью модели расширенной записи, используйте метод getLabel().
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.
Параметры:
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
property | String | Y | N |
Возвращаемое значение:
Type | Description |
---|---|
Mixed | The string value of the object property. |
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.
Возвращаемое значение:
Type | Description |
---|---|
Boolean | The method returns 'true' if the record has an attachment; otherwise, it returns 'false'. |
Пример:
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").
Возвращаемое значение:
Type | Description |
---|---|
Void | Метод не возвращает значение. |
Пример:
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.
Возвращаемое значение:
Type | Description |
---|---|
Integer |
|
Пример:
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.
Возвращаемое значение:
Type | Description |
---|---|
Boolean | This method returns the value of the is_vcs_enabled attribute of the record table. |
Пример:
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.
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
condition | String | N | '' |
Возвращаемое значение:
Type | Description |
---|---|
Boolean | This method returns 'true' if the record meets the condition specified; otherwise; it returns 'false'. |
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.
Возвращаемое значение:
Type | Description |
---|---|
Record or Boolean | If this is the first call, this method returns the first record in the query. If the query is empty, this method returns 'false'. |
Пример:
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.
Параметры:
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
column | String | Y | N |
Возвращаемое значение:
Type | Description |
---|---|
Void | Метод не возвращает значение. |
Пример:
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.
Параметры:
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
column | String | Y | N |
Возвращаемое значение:
Type | Description |
---|---|
Void | Метод не возвращает значение. |
Пример:
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.
Возвращаемое значение:
Type | Description |
---|---|
Void | Метод не возвращает значение. |
Пример:
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.
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
attributes | String or Array | Y | N |
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).
Возвращаемое значение:
Type | Description |
---|---|
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. |
Пример:
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"}
Пример:
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.
Параметры:
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
flag | Boolean | Y | N |
Возвращаемое значение:
Type | Description |
---|---|
Void | Метод не возвращает значение. |
Пример:
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.
Параметры:
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
maxNumRecords | Integer | Y | N |
Возвращаемое значение:
Type | Description |
---|---|
Void | Метод не возвращает значение. |
Пример:
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.
Параметры:
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
property | String | Y | N |
value | String | Y | N |
Возвращаемое значение:
Type | Description |
---|---|
Void | Метод не возвращает значение. |
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.
Параметры:
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
reModelId | String | Y | N |
If the reModelId parameter is equal to 'null', the REM, related to the record, will be detached.
Возвращаемое значение:
Type | Description |
---|---|
Void | Метод не возвращает значение. |
Пример:
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.
Параметры:
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
property | String | Y | N |
value | String | Y | N |
Возвращаемое значение:
Type | Description |
---|---|
Void | This property does not return a value. |
Пример:
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.
Name | Type | Mandatory | Значение по умолчанию |
---|---|---|---|
enable | Boolean | N | true |
Type | Description |
---|---|
Void | This property does not return a value. |
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: )"
Возвращаемое значение:
Type | Description |
---|---|
Integer |
|
Пример:
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.
Возвращаемое значение:
Type | Description |
---|---|
Void or Integer |
|
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