Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Record Extended Model allows you to extend a set of table attributes. 

The table structure of REM repeats the dictionary structure with tables and columns. Instead of columns, Attributes (sys_re_attribute) are used in REM. You can connect REM attributes with a table within the Model (sys_re_model). Besides, you can create attribute collections as universal sets of attributes that can be used in several models at the same time. 

You can access to dictionaries related to REM through the Record Extended Model (REM) menu category. 

REM concept

ttps://home.simpleone.ru/record/sdlc_goal/159541824313375640

https://docs.google.com/spreadsheets/d/1dhiztB3hBmlEq2D1xFBrCE-tUGk9giKWgsmk6SSACAQ/edit#gid=614486133

What is REM?

To answer this question, we need to provide some theory first.

Thesis 1

In SimpleOne, you can handle with data which is represented as records in tables that have a specified attribute set. Records appear in tables and they have these attribute values given.
Thesis 2


Every table has its own data model stipulated specified by the business-logic. The data model is represented by the column set (their amount, types, links with another system objects, and so on). This data model can be extended with child table with the same attribute set as a the parent one, and an individual attributes inaccessible from the parent table, as an addition. For example, the diagram below shows that all attributes of the User table are inherited by the Employee table:

Attributes extension curcuit diagramcircuit diagram

Image Removed

транскрибация записи

Первый тезис.

Наша система - это возможность управления данными, которые представлены в виде таблиц. Сами таблицы имеют определенный набор атрибутов. В этих таблицах появляются записи, у которых заданы значения этих атрибутов.

Второй тезис

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

Если есть сущности, обладающие общностью, например, итсм таски, мы создаем соответствующую таблицу и от нее наследуем инциденты, реквесты и так далее. Получили, к примеру, 6 таблиц, у которых 70% атрибутов пересекается, и у каждой таблицы 30% свои атрибуты. В таких масштабах наследованием пользоваться удобно. Совсем другое дело, когда дочерних таблиц много.

Когда у нас есть какой-нибудь каталог запросов, в этом каталоге не 6 запросов, а 306) то наследование становится неудобным. И придумали еще один способ, как можно расширять модель данных. Причем это расширение будет справедливо для конкретной записи, а не в целом для набора записей в таблице. Что было сделано:

Мы сделали такую таблицу, в которой хранятся модели, эти модели могут применяться для какого-то типа записей для какой-то таблицы, и этой записи они могут добавить несколько специфичных атрибутов, которые описаны в этой модели. Получается, модель - это некий синоним шаблоона запроса.

Физически: есть табличка с этими модельками, к каждой модельке привязаны эти специфичные атрибуты, и есть запись, для которой эта модель может примениться. Применение модели означает, что когда мы создаем запись, мы: (1) задаем те значения, которые должны быть у этой записи, (2) и для этой записи мы создаем набор вспомогательных записей, в которых указано, что к этогй записи для специфичногог атрибута 1 такое-то значение, для атрибута 2 такое-то значение, и так далее. Получается: запись обладает атрибутами, которые есть у таблицы, и теми атрибутами и их значениями, на основании той модели с этой записью связанной. Для этой записи создается набор пар "атрибут : значение", набор связанных записей, которые указывают на эту запись, это указание на тот атрибут из этой модели и его значение, специфичное для этой записи. В данном случае у нас получается, что у этой записи нет колонок, но есть вспомогательные записи, которые содержат указания на атрибут и его значение. Но этот атрибут не является частью таблицы.

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

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

Атрибут - это абстрактная сущность, похожая на обычную колонку таблицы, но ей не является по факту, но с точки зрения пользователя это как будто бы еще одно поле, которое ты заполняешь каким-то значением, но опять же оно хранится не как какое-то значение, а как отдельная запись в вспомогательной таблице.

Без модели, атрибут не имеет смысла, при создании атрибут связывается с моделью. Мы говорим, что у нас есть запрос, и он будет создан по такой-то модели. Это значит, что помимо штатных полей запроса мы еше запорлним вот эти вот атрибуты, которые пришли из модели.

Это полезно, когда мы оперируем большим количеством разнородных сущностей, которые должны обладать сходством. Простой пример: запросы. Там есть 10 базовых полей и куча отличающихся, и они созданы по сотне моделей. Плодить сто таблиц и этим управлять - это лишняя трата ресурсов. Гораздо проще натравить модельку с атрибутами, чем целую таблицу делать.

Этими атрибутами нужно управлять так же, как обычными полями. Потому что с точки зрения пользователя, он просто заполняет форму. 

Порой, при работе в рамках одной таблицы, для расширенного сбора и последующей обработки информации, могут использоваться иные атрибуты, так называемые "переменные". Один из случаев, когда можно использовать такую функциональность, это когда в рамках одной таблицы, для разных записей нужны разные наборы атрибутов, а использование расширения таблиц, путем наследования, технологически неприемлемо (из-за большого количества специфичных полей в большом количестве наследуемых таблицах), а также влечет за собой увеличение трудозатрат на управление множеством специфических полей в наследуемых таблицах. Тогда необходимо использовать атрибуты расширенной модели записи.

Переменная записи это как бы поле, выглядит как поле, ведет себя как поле, но полем, т.е. объектом sys_db_column не является. Т.е. в “переменной” для определенной записи и в пользовательском интерфейсе, и в API можно задать значение, прочитать значение, изменить значение. На события, связанные с переменной и с ее содержимым, можно наложить необходимую для автоматизации бизнес-процесса логику. "Переменные" являются атомарным звеном и объединяются в модели записи или в коллекции атрибутов, и представляют собой расширенную модель записи. Коллекции могут включаться в разные модели записи. Модель записи определяется при создании записи путем выбора или предопределенного значения. 

Для целевой записи с определенной моделью записи можно задать значения переменных в виде ассоциированных с этой записью специальных записей, хранящих эти значения.

Image Added

When there are not many child tables, and the attribute overlap is high, this data model works fine. But when the child table number increases, and the attribute overlap decreases, the management of this data model becomes a challenge. Data model with big and complicated table inheritance structure has some disadvantages:

  • It is required to allocate more space for record storage.
  • Scripts are executed slower.
  • It is getting harder to configure the functionality related to the specified dictionary, such as data import, layout setting, etc.

Request Catalog can be taken as an example of such a table: a parent table for the catalog and a record in the table for each request template with specific attributes.

To deal with this issue, Record Extended Model concept has been created and implemented. Extension concept can be applied to a specified table record, giving some additional attributes to it.

When a record extension model is applied to a record, it means that an auxiliary record set is created for this record containing information about specific attribute values. So the record has attributes inherited from a table, and in addition, it has attributes sourced from the extension model.

Configuring extension models


Generally, to configure your extension model, you need to:

  1. Create an extension model.
  2. Create attributes and link them to the model.
  3. (optional) Configure the attribute collection.
  4. (optional) Configure model client script.

In the diagram below, you can see the difference between models and collections. Models are created with a specific attribute set that can only be used in this model. Collections contain attributes that can be applied to different models. 

Note

It is not recommended to create collections with many attributes. It is better to create one collection with one attribute. 

Image Added

Creating models


To create a model, To create a record extended model, please complete the steps below:

  1. Navigate to Record Extended Model → Model (REM) → Models.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply the changes.

Record extended model Extended Model form fields

FieldMandatoryDescription
NameYThe model name. 
TitleYThe model title. Can be specified in a language other than English.
Description
NThe model description. 
TableY

Reference to

a ActiveNSelect this checkbox to make the model active or inactive.IconNReduced image intended for the model identification.

the table affected by the model.

Note

Please note that after saving you cannot specify

a read-only table. To use such a table, please turn off this attribute first.

another table.


DescriptionNType model description. 
After insert scriptNSpecify a script that should be executed after a record is created. Develop it using JavaScript extended by the SimpleOne SimpleRecord Server
-Side API and Client
-Side
API
 methods.
ActiveNSelect the checkbox to make the model active or inactive.
IconNSmall image intended for model identification
 methods
.
Related
lists:

Attribute

Model client script

Model form element

Атрибут расширенной модели записи представляет собой элемент справочника атрибутов (запись в таблице sys_re_attribute, наследуемой от таблицы  sys_db_column). Для атрибута расширенной модели записи определены следующие поля:

Lists
AttributesList of the attributes linked to this model.
Model Form ElementsList of the form element linked to this model.
Used CollectionsList of applied collections
Model Client ScriptsList of the model client scripts linked to this model.


Note
  1. Do not create or add an attribute to a model if an attribute with the same name already exists in this model. 
  2. Do not rename an existing attribute if there is an attribute in the model with the name you want to enter.

Configuring attributes


In SimpleOne you can create attribute mapping for models and collections. Data mapping is the process of connecting a data field from one table to a data field in another table. It reduces the potential for errors, helps standardize your data, and makes it easier to understand your data because it establishes direct relationships between your data across multiple tables at once.

To create an attribute, To create a record extended model attribute, please complete the steps below:

  1. Navigate to Record Extended Model → Model (REM) → Attributes.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply the changes.

Attribute form fields

FieldMandatoryDescription
RE model
ContainerYReference to a previously created model.
Attribute TypeYSpecify the attribute type. 
TitleYSpecify the attribute title. You can use Latin, Cyrillic letters, [0..9] numbers and the underscore symbol ( _ ).
Attribute NameYAttribute system name. This field is populated automatically. Latin letters, [0..9] numbers and the underscore symbol ( _ ) are allowed.
Map to ColumnN

Specify the target field to map the attribute value before the record is inserted (including business rules of the before type). This option allows you to quickly transfer attribute values to fields. The field is of the Reference type and has a reference qualifier, which allows for choosing columns of table defined in the model record and columns of its child tables.

Info
YSpecify a column type TitleYAn attribute title. Can be specified in a language other than English.Column nameYMap to ColumnN

Specify a target field to map the attribute value after the record is created.

Существуют ситуации, когда мы хотим создать какую-то запись и не используем штатные механизмы создания записей, а используем только механизм создания атрибутов, моделей. Быстрая трансляция значения атрибутов в поля. Полезно, когда идет речь о дополнительной валидации.

Comments

If the target field is mandatory, the value will be saved before it is processed by the server validation engine.

Also, if the target field is mandatory, it should not be displayed on the form, otherwise the client validation engine may hamper the record saving.


Note

Mapping via the Map to Column field is available only if the column type of the attribute is equal to the target column type.

The following message appears if there is no target column in the table: 

Panel

Attribute "{attribute_name}" mapping error, reference column not found in the table


CommentsNPut some comments here describing your attribute.
ActiveNSelect the checkbox to make the attribute active or inactive.
Read OnlyNSelect the checkbox to make the field added with this attribute read-only.
MandatoryNSelect the checkbox to make the field added with this attribute mandatory.
Type Specification tab
Dependent on ColumnY

Specify a column with reference to the Table (sys_db_table).

The field appears when one of the following options is selected in the Attribute Type field:

  • Field Name
  • Conditions
  • Template.
Maximum LengthN

Specify a maximum value length for the attribute value. The value length cannot exceed the allowable length for the specified data type.

The field appears when one of the following options is selected in the Attribute Type field:

  • String
  • Text
  • URL
  • Password
  • Script
  • Journal Input
  • HTML
  • Encrypted Password
  • Translated Text
  • Record Class.
Choice Table N

Reference to a table.

The field appears when the Choice option is selected in the Attribute Type field.

Choice FieldY

Reference to a particular column of the table specified in the Choice Table field.

The field appears when the Choice Table field is populated. 

Choice TypeY

Define whether the None option is applicable for the field. Available options: 

  • Dropdown with --None--
  • Dropdown without --None-- (specify a default value).

If the Dropdown without --None-- is chosen, the Default value field becomes mandatory.

The field appears when the Choice option is selected in the Attribute Type field. 

Extra AttributesN

Specify additional configurations for the field. 

For example, enter the text below to apply radio buttons style to the choice field:

choice_decorator=radio

The field appears when one of the following options is selected in the Attribute Type field:

  • Choice
  • Conditions
  • Image.
ReferenceY

Specify a table with the values you need.

The field appears when the List or Reference option is selected in the Attribute Type field.

On DeleteN

Select the action to take when the referenced recordis deleted. Available options:

  • No action – no actions will be taken.
  • Set NULL – the reference to this record will be deleted from the field (the value will be equal to 'null').
  • Cascade – the record containing reference to it will be deleted as well.
  • Restrict – deletion the referenced record is forbidden.
  • Set default value– the reference to it will be changed to the default value defined at the Default Value tab.

The field appears when the Reference option is selected in the Attribute Type field.

Default Value tab
Default ValueN

Specify the default value that will be populated to the field when creating a new record. This field may be specified by a JavaScript scenario as well.

Use Dynamic DefaultNSelect the checkbox if you want to generate the default value dynamically.
Dynamic DefaultY

This field only appears when the Use Dynamic Default checkbox is selected.

Select the script from the Dynamic Default Values (sys_default_value_dynamic) dictionary, so its execution result will be automatically calculated and entered into this field; this value will be the default value for the column specified.

  1. The script must be preliminarily created in the Dynamic Default Values (sys_default_value_dynamic) dictionary; otherwise, you will not be able to choose it.
  2. You can only choose active scripts (the Active checkbox is selected). 
Reference Qualifier
Reference Qualifier TypeN

Specify the type of the reference qualifier. Available options:

  • Simple
  • Dynamic

The field appears when the List, Reference or Field Name option is selected in the Attribute Type field.

Reference Qualifier ConditionN

Configure filters using the Condition Builder.

The field appears when the Simple option is selected in the Reference Qualifier Type field.

Dynamic Reference QualifierN

Select the dynamic reference qualifier from the list. 

The field appears when the Dynamic option is selected in the Reference Qualifier Type field.

Reference Qualifier FixedN

Select the checkbox to fix filters in breadcrumbs. This functionality will block using the Condition Builder functionality.

The field appears when one of the following options is selected in the Attribute Type field:

  • List
  • Reference
  • Field Name.

Configuring attribute collections


Attribute collections are implemented to user Many-to-Many Relationships, so they allow you to reuse the same attributes accross models instead of adding them separately to each model where necessary.

Simplified concept of use is:

  1. Create a collection record as described below.
  2. Fill it with previously created attributes or create new ones using the Attributes related list.
  3. Relate this collection with previously created models using the Used in Models related list.

After that, all the attributes contained in this collection are used by all models this collection relates to.

Info
  • If you want to use attribute mapping in a collection, you need to specify a table in the Table field of a collection. Otherwise, leave the Table field empty.
  • Collections with the populated Table field can only be added to models with the same table specified or to models of child tables.

To create a collection, complete the steps below:

  1. Navigate to Record Extended Model (REM) → Collections.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply the changes.

Collection form fields

FieldMandatoryDescription
TitleYSpecify the collection title.
ActiveNSelect the checkbox to make the collection active or inactive.
TableN

Specify the table to which the collection is related.

Related Lists
AttributesIn this related list, you can create a new attribute related to this collection or select an existing one from the dictionary.
Form ElementsIn this related list, you can create a new form element related to this collection or select an existing one from the dictionary.
Used in ModelIn this related list, you can create a new model related to this collection or select an existing one from the dictionary.
Client ScriptsIn this related list, you can create a new model client script related to this collection or select an existing one from the dictionary.


Note
  1. Do not rename an existing attribute in the collection if there is an attribute in the model or in the collection linked to the model with the name you want to enter.
  2. The same collection and model cannot be linked to each other more than once.
  3. Model and collection that have at least one eponymous attribute matching the model attribute cannot be bound between each other.

Configuring model client scripts


To create a record extended model client script, please complete the steps below:

  1. Navigate to Record Extended Model → Model (REM) → Model Client Scripts.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply changes.

Record extended model client script Model Client Script form fields

FieldMandatoryDescription
Name
Client
YDefine the client script name.
This field is mandatory.RE model
ContainerYReference to
a previously created model. This field is mandatory
the model or collection.
TypeY
The

Specify the script type. Available options:

  • onLoad 
it
  • the script starts when the system displays the form for the first time before users
will
  • enter data. Generally, onLoad
 scripts
  •  scripts perform manipulations on the client
-
  • side with the current form or
set
  • default record values
;
  • set.
  • onChange 
it
  • the script starts when the specified field
in
  • on the form
is
  • has been changed
;
  • .
  • onSubmit 
this
  • the client-side script can cancel form
submitting RE attribute
  • submission by returning 
false;
  • onCellEdit - this client-side script starts at the moment when some cell is to edit.
    • oldvalue - the old value for the cell that was edited;
    • newValue - the new value for the cell that was edited;
    • table - the table name of the cell being edited (for example, sys_db_table); 
    • sysId - the ID of the record relevant to the cell being edited;
    • callback - if this variable is equated to FALSE, then subsequent scripts will not run; otherwise, they will execute.
    • 'false'.
    AttributeN
    Reference to a previously created model attribute. This field is mandatory when the onChange script type is chosen.
    DescriptionNClient script description.
    ActiveNSelect
    this checkbox
    the checkbox to make the script active or inactive.
    OrderN
    Client
    Specify client script execution order. Scripts are executed in ascending order.
    ScriptNSpecify
    a client script. Develop it using JavaScript extended by the SimpleOne Client-Side API methods
    the client script.

    Configure model form elements


    You can arrange the fields of your model attributes in a particular order and position, as you can do with form layouts. Group attributes by common features and give them a title. In the screenshot below, custom model attributes are divided into two columns:

    Image Added

    Tip

    If you want to define a title for a group of attributes organized in one block, use the Begin element.

    The title will appear on the relevant page of the Self-Service Portal.

    To change the order of the displayed attributes, perform the following steps:

    1. Navigate to Record Extended Model (REM) → Models.
    2. Open the model you need.
    3. Scroll down to the Related Lists area and open the Model Form Elements tab.
    4. Arrange the attributes by changing the value in the Position field. 

      Tip

      Use inline editing: double-click on the cell in the Position column, enter the value and press Enter to save changes. 

      Image Added


    To configure a model layout, perform the following steps: 

    Anchor
    add split elements
    add split elements

    1. Navigate to Record Extended Model (REM) → Models.
    2. Open the model you need.
    3. Scroll down to the Related Lists area and open the Model Form Elements tab.
    4. Click New and fill in the fields.
    5. Click Save or Save and Exit to add the element.

    Model Form Element form fields

    FieldMandatoryDescription
    ContainerYReference to a previously created model. If the element is created from the related list, the field is populated automatically.
    PositionYDefine the order in which the element will be displayed on a form.
    Block ElementY

    Specify the type of the splitter. Available options:

    • Begin – use this element to define the beginning of block of fields. You can define the name of a group in it. When selected, the Block Title field is displayed.
    • Split – use this element to divide the field into columns.
    • End – use this element to define the end of the block of fields.
    Block TitleN

    Define the title of the group of fields. The title will be displayed above the attributes group on the relevant page of the Self-Service Portal.

    Info

    This field appears when the Block Element value is Begin.



    Table of Contents
    absoluteUrltrue
    classfixedPosition