Relations, references and mapped fields: model and API
Section titled “Relations, references and mapped fields: model and API”This page is for integrators and developers who read or write relation definitions, traverse related entries through the API, or need the exact rules behind reference fields, mapped fields and navigation links.
This page covers the distinct — but easily confused — mechanisms OSOS uses to link data across entities, all owned by the data-service:
- Data relations (
DataRelation) — first-class, queryable definitions of how one entity relates to another. They power the “related entries” tabs, sub-lists, the entity Joiner, and relation-sourced reactions. - Reference fields —
Entity-typed fields on an entity that hold the actual pointer to a referenced entry (thesource/sourcesconfiguration). - Mapped fields — fields whose value is copied or synced from a referenced entry, governed by an update-mode policy.
It also documents navigation links (LinksService) — the sidebar link tree and shareable system links — because that area shares the “links & references” vocabulary.
All entity/entry-scoped endpoints below are mounted on DataRelationController, which requires the Auth2 authentication strategy and runs the entityVoter authorization voter for every operation.
Concept map
Section titled “Concept map”| Concept | Where it lives | What it stores | Direction |
|---|---|---|---|
| Data relation (incoming) | DataRelation document | Explicit definition owned by dataEntity, pointing at a targetField on targetEntity | Incoming (relationType = 1) |
| Data relation (outgoing) | Derived at read time from the entity’s own reference fields | Synthetic, never persisted | Outgoing (relationType = 0) |
| Reference field | DataEntityField with dataType = Entity and a source/sources | The referenced entity + query used to pick an entry | n/a (field-level) |
| Mapped field | DataEntity.dataSources[] + field-level mapping | fromFieldId → toFieldId value copy with an updateMode | n/a (value sync) |
| Navigation link | LinkDataEntry (link entity) | Sidebar node pointing at a module/view/page/report | n/a |
How entities link
Section titled “How entities link”Before the model details, it helps to see the two everyday ways an administrator connects entities in the product:
- Reference field — a field of data type Entity on entity A that points to entries of entity B. Internally the reference is stored as a universal pointer,
ReferenceProperty, a{ dataEntity, dataEntry }pair (entity id + entry id), usually accompanied by a_resolvedblock carrying the related entry’s display title. Storing the pointer rather than plain text keeps the link stable even if the target entry’s display title later changes. - Data relation — a first-class, named relationship between two entities (incoming/outgoing), managed from the Relations tab of the entity. Relations let you traverse related entries, show them as sub-lists, build Joiner virtual entities, and drive relation-sourced reactions.
Data relations are also what let you build nested, hierarchical organizational structures: an entity representing an organization can act as the parent of child entities representing its departments or projects, so data is organized according to the parent–child hierarchy between them.
The DataRelation model
Section titled “The DataRelation model”A DataRelation is a document in the data-service. It extends Identified<UUID> and implements the shared IDataRelation interface.
| Field | Type | Required | Notes |
|---|---|---|---|
id | UUID | (server) | Primary key. |
specificationVersion | number | yes | Defaults to 1. |
dataEntity | UUID | yes | The entity that owns this relation definition. |
name | LocalizedValue | yes | Display name; validated by LanguagesService.validateName. |
description | NullableLocalizedValue | no | |
icon | Icon | yes | |
targetEntity | UUID | yes | The entity on the other end. |
targetField | string | yes | fullNormalizedName of the reference field that realizes the link (see below for which side it lives on). |
relationType | DataRelationTypeEnum | yes | Outgoing = 0, Incoming = 1. |
normalizedName | string | (auto) | Machine name, unique per dataEntity. Pattern-validated (NormalizedNameValidation). Since 1.6 |
isImplicit | boolean | no | Defaults to false. Implicit relations are read-only (see below). |
updateIdentifier | string | yes | Optimistic-concurrency token (a UUID). Since 1.6 |
The NewDataRelation request body for create excludes id and updateIdentifier (both are server-assigned); the PATCH body excludes only id.
Incoming vs. outgoing
Section titled “Incoming vs. outgoing”This is the single most important thing to understand:
- Incoming relations are the stored
DataRelationdocuments. They describe entries intargetEntitythat point intodataEntityvia a reference field named bytargetField(that field lives ontargetEntity). In the product, an incoming relation is one where the current entity acts as the “parent” entity, defined and modified by an administrator from the Relations tab. - Outgoing relations are computed on the fly from
dataEntity’s own reference fields (getEntityRelationFieldsWithoutADT()), never persisted. Each of the entity’s reference fields yields one; their syntheticidis a composite key (see below) and theirtargetFieldis thefullNormalizedNameof a field ondataEntityitself. In the product, an outgoing relation is one where the current entity acts as the “child.”
transformToRelationDto reflects this asymmetry: for an incoming relation it resolves the field on the related (target) entity; for an outgoing relation it resolves the field on the owning entity.
The V2 list/count endpoints return both buckets. For example findV2 builds outgoingRelations by walking each relation field’s sources[] (or the legacy single source) and emitting one synthetic DataRelation per source with id = "{dataEntity.id}:{field.id}:{source.entity}".
Managing relations from the Relations tab
Section titled “Managing relations from the Relations tab”In the product, both incoming (inbound) and outgoing (outbound) relations are viewed from the entity’s Relations tab, each shown as a card carrying the relation’s name, icon, related entity, and relation field. Clicking a card opens a form with the relation’s details; entering new values and clicking Finish saves the change. To remove a relation, click the delete icon next to it: a confirmation prompt appears, and once confirmed the relation is permanently deleted and cannot be undone.
Implicit relations
Section titled “Implicit relations”A relation with isImplicit = true is system-managed and locked:
PATCHthrowsImplicitRelationUpdateException(IMPLICIT_UPDATE_RESTRICTION).DELETEthrowsImplicitRelationDeleteException(IMPLICIT_DELETE_RESTRICTION).
System-wide list/count endpoints hide implicit relations unless you opt in. applyImplicitFilter / applyImplicitWhere merge an isImplicit: false constraint using an explicit {and: [...]} conjunction (so a caller’s nested or cannot leak implicit rows) whenever the includeImplicit query flag is false (the default). Since 1.8
Example: the “Themes” incoming relation on the Application Shell Since 1.10
Section titled “Example: the “Themes” incoming relation on the Application Shell Since 1.10”The core Application Shell entity (SHELL) shows the incoming-relation pattern above in a system-managed form. Data-service migration 1.10.0-a28 creates the implicit relation SHELL_THEMES_RELATION on it:
| Property | Value |
|---|---|
dataEntity | SHELL |
targetEntity / targetField | THEME / shell |
relationType | Incoming |
normalizedName | themes |
name | “Themes” / “السمات” — “Themes that use this application shell” |
isImplicit | true |
The Application Shell has no outgoing field to themes: the relation simply lists the THEME entries whose shell reference field points at the shell entry. Because it is implicit it cannot be edited or deleted through the Relations API, and it is hidden from system-wide listings unless you pass includeImplicit=true. The migration writes the relation directly, so no DataRelationCreatedEvent is published for it.
An Application Shell entry is stored layout data that a theme can point at. The 1.10 web client does not render it, and no shell builder is part of 1.10.
normalizedName and concurrency
Section titled “normalizedName and concurrency”On create, if the client supplies normalizedName it must be unique within the owning entity (DataRelationNormalizedNameDuplicateException / DATA_RELATION_NORMALIZED_NAME_DUPLICATE); otherwise it is auto-derived from name via generateUniqueNormalizedName(name, existingNames, 'relation'). The uniqueness check runs against all sibling relations of the same dataEntity.
updateIdentifier is an optimistic-lock token. On create it is set to a fresh v4(). On update, if the client sends an updateIdentifier that differs from the stored one, the write is rejected with UpdateIdentifierConflictException; otherwise the server rotates it to a new UUID. Since 1.6
Relations API
Section titled “Relations API”All routes below are on DataRelationController. {entity} accepts an entity id or normalized name in its space (getEntityByIdOrNormalizedNameInSpace).
| Method & path | Handler | Purpose |
|---|---|---|
POST /v1/entities/{entity}/relation | create | Create a relation for {entity}. Publishes DataRelationCreatedEvent. |
GET /v1/entities/{entity}/relation | find | List stored (incoming) relations of {entity} as DataRelationDto[]. |
GET /v2/entities/{entity}/relation | findV2 | Return {incoming, outgoing} (DataRelationListDto). |
GET /v1/entities/{entity}/relation/count | count | Count stored relations (optional where). |
GET /v2/entities/{entity}/relation/count | countV2 | {incoming, outgoing} counts (DataRelationCountDto). |
GET /v1/entities/{entity}/relation/{id} | findById | One relation of {entity} as DataRelationDto. |
GET /v1/relations | findAll | System-wide list. includeImplicit (default false); limit clamped to [1, 500], default 100. |
GET /v1/relations/{id} | findOneById | One relation by id (supports composite ids). |
GET /v1/relations/count | countAll | System-wide count. includeImplicit (default false). |
POST /v1/entities/joiner/relations | findEntitiesRelations | Given {dataEntities: string[]}, return the union of their incoming relations. |
GET /v1/entities/target/{targetEntity}/relation | findRelationsByTargetEntity | Undocumented, system-service only. Returns [{relationId, targetField}]. |
PATCH /v1/entities/{entity}/relation/{id} | updateById | Update (blocked for implicit). Publishes DataRelationUpdatedEvent with a raw diff. |
DELETE /v1/entities/{entity}/relation/{id} | deleteById | Delete (blocked for implicit). Publishes DataRelationDeletedEvent. |
Related-entries endpoints
Section titled “Related-entries endpoints”Given an entity, an entry, and a relation, these return (or count) the entries on the other end. Internally each resolves the relation, loads the targetEntity, and delegates to DataEntryService factories with a relation context of {targetField, entityId, entryId, relationType}.
| Method & path | Handler | Extra inputs |
|---|---|---|
GET /v1/entities/{entity}/entries/{entryId}/relations/{relationId} | findRelatedEntries | filter, include_virtual |
GET /v2/.../relations/{relationId} | findRelatedEntriesV2 | filterCriteria, search, include_virtual |
GET /v3/.../relations/{relationId} | findRelatedEntriesV3 | + appliedQuickFilters, appliedTagsFilters → {entries, tags} |
GET /v1/.../relations/{relationId}/kanban/{categoryFieldId} | findRelatedEntriesKanbanView | grouped board + categoryId, tags/quick filters |
GET /v1/.../relations/{relationId}/count | findRelatedEntriesCount | where, include_virtual |
GET /v2/.../relations/{relationId}/count | findRelatedEntriesCountV2 | whereCriteria, search |
The V3 route accepts appliedTagsFilters, whose tag criteria are resolved through TagsService.getTagsFilterCriteria(targetEntity.getId(), appliedTagsFilters) before being applied.
Composite (field-level) relation IDs
Section titled “Composite (field-level) relation IDs”relationId is polymorphic. DataRelationRepository.findRelationById accepts:
- A plain UUID — resolved with
findById. {entityId}:{fieldId}:{sourceEntityId}(3 parts) — resolves the relation fieldfieldIdonentityId, verifiessourceEntityIdexists in the field’ssources[](or matches the legacy singlesource), and synthesizes an outgoing relation withtargetEntity = sourceEntityIdandtargetField = field.fullNormalizedName. Unknown field or source →RelationNotExistException(RELATION_NOT_EXIST).{entityId}:{fieldId}(2 parts) — same, using the field’s legacysourceastargetEntity.
This is why the kanban and related-entries routes work for outgoing relations that have no stored DataRelation document.
Create example
Section titled “Create example”POST /v1/entities/orders/relationContent-Type: application/json
{ "specificationVersion": 1, "dataEntity": "…orders-entity-id…", "name": { "en": "Line items", "ar": "…" }, "icon": { … }, "targetEntity": "…order-lines-entity-id…", "targetField": "order", // field on order-lines that points back to orders "relationType": 1 // Incoming // normalizedName optional; updateIdentifier must be omitted}Events
Section titled “Events”Relation mutations publish domain events on the service bus (correlationId = traceId, plus sticky attributes for userId, delegateeId, delegationId, spaceId):
DataRelationCreatedEvent(relation, userId)DataRelationUpdatedEvent(updatedRelation, userId, rawDiff)—rawDiffcomputed withjust-diffbetween the pre- and post-update documents.DataRelationDeletedEvent(relation, userId)
Reference fields
Section titled “Reference fields”A reference field is a DataEntityField with dataType = Entity that carries a source. getEntityRelationFieldsWithoutADT() selects them: dataType === Entity, has source or a non-empty sources[], is not a virtual field, and its source is not an ADT (audit) entity.
source?: UUID— deprecated single source entity id. Still honored across the code (the composite-id 2-part form and the “single source (legacy)” branch infindV2).sources?: FieldSources[]— the current model. EachFieldSourcesentry:
| Property | Meaning |
|---|---|
entity | Source entity id the field references. |
entriesSource | Optional query id used to populate the picker (nullable). |
entriesSourceParameters | Parameters bound to a parameterized entriesSource. |
entriesSourceDependencies | Full normalized names of fields the query expressions depend on (computed by the backend to know when to refresh the dropdown). |
relatedTo | If non-null, the parent field’s fullNormalizedName this field cascades from. |
relation | The DataRelation id used for cascaded entries (only meaningful when relatedTo is set). |
Reference field configuration
Section titled “Reference field configuration”When an administrator configures a reference field, they set:
- The source that supplies the selectable options: a store, collection, query, or an entity/view/module.
- Single vs. multiple selection, and tree vs. flat selectors.
- Context filter pointers (such as Me, My groups, My roles, My org unit) to scope the options to the current user.
Special cases
Section titled “Special cases”- Cascaded-parent filtering — a reference field’s options can be constrained by the value of another reference field on the same entry (this is what
relatedToandrelationabove express). - Circular-relation denial — the platform prevents circular relations that could cause infinite references.
- Resync — a reference field can declare fields whose change recalculates it (
resyncFields), with a preserve value on edit option (preserveValueOnEdit) to keep the recalculated value rather than overwrite it.
Display and selection behaviour Since 1.8
Section titled “Display and selection behaviour Since 1.8”- A collection reference always shows its resolved main title in view mode. A reference that points at a data collection rather than an entity carries only an id plus a resolved main title, so there is no
mainTitleFieldto derive from it. View mode renders the main title regardless, so the value is displayed instead of coming out blank. - Search-picked values survive a dropdown reload. Reference pickers are backed by server-side search, so the option list only ever holds the current page of results. A field that holds multiple values keeps every id the user has already selected, even after the dropdown reloads its options for a different search term — the selection, not the visible page, is authoritative, and deselecting an id still removes it.
- An unresolved single value normalizes to empty. On a single-value reference field, an id that resolves to no payload settles as an explicit empty value rather than lingering as a broken reference or propagating an undefined one.
Mapped fields
Section titled “Mapped fields”Mapped fields copy values from a referenced entry into the current entity when an entry is created or updated. This is implemented by MappingFieldService.
The update modes appear in the field settings as Local Update (Local),
Never (Never), From Parent Only (ParentOnly) and 2 way (TwoWay).
In the form, a mapped field in Never or From Parent Only mode is read-only;
2 way is offered only when the mapped field’s required setting matches its
source field’s, and a mapped field inside a repeatable block that differs from its
reference field’s block can only use Never or From Parent Only.
Configuration
Section titled “Configuration”Three pieces of config drive mapping:
- Entity-level
dataSources: DataEntityFieldSources[]— each source is{ referenceEntity, referenceField, mappedFields: MappingFields[] }.referenceFieldis the id of the reference field on this entity whose selected entry supplies the values. - Per-mapping
MappingFields—{ fromFieldId, toFieldId, updateMode }, wherefromFieldIdis a field on the referenced entity andtoFieldIda field on this entity. - Field-level
mapping: DataEntityFieldMapping—{ enabled, referenceFieldId, sourceFieldId, updateMode, searchMode }. A target field is only written ifmapping.enabledis true.searchMode(MappedFieldSearchModeEnum:None,Full,StartsWith,Partial) controls how the mapped value participates in search.
Update modes
Section titled “Update modes”MappedFieldUpdateModeEnum decides who wins when the source and local values disagree. Behavior is implemented in handleMappingFields:
| Mode | Value | Effective behavior |
|---|---|---|
Local | 0 | Keep the local value unless the reference changed (isReferenceChanged); on a reference change, pull the source value. Preserves local edits between reference changes. |
Never | 1 | Keep the local value whenever it is defined (or when there is no source field); otherwise seed from source. Existing local values are never overwritten. |
ParentOnly | 2 | Falls through to the default branch: always take the source (fromFieldValue). Source is authoritative. |
TwoWay | 3 | If the reference changed and the caller did not set childToParentHighPriority, take the source; otherwise keep the local (child) value. Lets a child edit propagate back toward the parent. Since 1.6 |
isReferenceChanged compares the referenced entry id currently stored on the entry against the incoming sourceEntryId. In the entity-wide pass (getValuesByEntityDataSources), handleMappingFields is called with childToParentHighPriority = true, so under TwoWay the child’s value takes precedence.
Resolution flow
Section titled “Resolution flow”getValuesByEntityDataSources(spaceId, dataEntity, dataEntry, isUpdateMode) returns a Map<toFieldId, value> (values may be arrays for repeatable blocks):
- For each
dataSourcesentry, load thereferenceEntity(cached in a local map) and locate thereferenceFieldby id. - Read the reference value at
referenceField.fullNormalizedName. If empty and the field’soptions.autoSelectFirstValueis set, fall back toDataEntryService.getDefaultFirstValue. If still empty and the field is calculated or has an on-form-opened trigger, runcalculateField. - If the reference field sits inside a repeatable block (
isParentBlockRepeatable+blockNormalizedName), iterate each block instance; a block with nodataEntryreference pushesnullfor every mapped target. Otherwise resolve the single referenced entry. - For each mapped field,
handleMappingFieldsloads the source entry (state = Active,isInvalid = false) and applies the update-mode rules above. Repeatable target blocks are matched by the block whose reference field’sdataEntry === sourceEntryId.
Only fields whose mapping.enabled is true are populated; disabled targets are skipped.
Propagation after the source changes
Section titled “Propagation after the source changes”Separately from the create/update pass above, an event handler pushes changes
made on a parent entry to entries that map from it, for mapped fields in
ParentOnly or TwoWay mode; for a TwoWay mapped field, a change made on the
child is also written back to the parent entry
(UpdateMapFieldValueEntryCreatedHandler /
UpdateMapFieldValueEntryUpdatedHandler in data-service). Local and Never
targets are never refreshed from a later parent change.
Navigation links
Section titled “Navigation links”LinksService builds the authenticated sidebar tree — a different kind of “reference”: a link node that points at a resource. Links are entries of the link entity (LINK_ENTITY_NORMALIZED_NAME).
LinkType values: Module = '0', View = '1', Page = '2', Report = '3', Untyped = '4'.
Reports are web-only. A report link opens only in the web app; on mobile it resolves to a
NotSupportedLinkand cannot be navigated to.
Sidebar links (the Links entity)
Section titled “Sidebar links (the Links entity)”Sidebar entries are managed through the Links entity, whose entries can be either manually owned or system-owned. System-owned links are maintained automatically: when a module, view, or report is created, updated, or deleted, the system creates, updates, or removes the corresponding Links entry. Manually added entries let an administrator place custom nodes in the sidebar, choosing type (Module, View, Page, Report, Untyped), icon, name, description, parent (for hierarchy), publish state, and permissions (Authenticated, Anonymous, Restricted, Everyone). Entries are ordered by the Order field, smallest to largest. Each manual entry also has a Target section whose sub-fields depend on the type: Link (the URL, used when the type is Uncategorized), Target ID (auto-filled for system-owned entries), and Target View Action (the view link, used when the type is View). Entries with system ownership inherit all their settings from their source — a View entry, for example, adopts its settings from the view configuration.
getLinksForSidebar(domain, spaceId, userId, delegationId?) assembles the tree:
- Anonymous (no
userId): includes links whoseauthentication.type.idis0(Anonymous) or2(Everyone), plus1(Authenticated) links whosevalue.type.idis'0'. - Authenticated: includes types
1and2, plus3(Restricted) links where the user (or one of their groups) appears invalue.authentication.users/groups. - All links must be
published: true,state: 1, match the domain (emptydomain= all), and satisfy sharing (ApplicationSharingLevelEnumPublic, or Private/Shared scoped tospaceId). Ordered byvalue.order ASC, thenvalue.title.en ASC. - When a
delegationIdis present,filterLinksByDelegatedPermissionsdrops view/report/page links whose target id is not among the delegatee’s allowed resources. - The tree is assembled by parent id; a
Modulenode with no children is pruned. View links whose parent is hidden are skipped.
Related helpers: createLinkForModule builds a system-owned module LinkDataEntryValue; archiveExistingLinks(targetId, userId, correlationId) sends an ArchiveDataEntriesCommand for all active links pointing at a target (used to clean up when the underlying resource goes away).
System links (shareable links)
Section titled “System links (shareable links)”Besides sidebar links, OSOS provides system links — shareable, token-based links that resolve to a specific target: a data view, a page/generic view, a report, or a module. They carry:
- Token — a unique token bound to the target; the system mints a signed link and resolves the token when the link is opened, directing the visitor to the intended target.
- Target — the view, page, report, or module the link resolves to.
- Authentication type — anonymous (public access without signing in) or authenticated (requires login).
- Validity / expiry — a validity period and expiry date; a link can be enabled, disabled, have its validity updated, or be removed.
Anonymous links expose public views to unauthenticated visitors; to protect these views the system adds a human-verification (CAPTCHA) step, and the target can be inspected before sharing via Preview Mode.
Constraints & gotchas
Section titled “Constraints & gotchas”targetFieldside depends on direction. Incoming:targetFieldlives ontargetEntity. Outgoing: it lives on the owningdataEntity. Get this wrong andtransformToRelationDtowill fail to resolve the field.- Outgoing relations are ephemeral. They have composite ids and no document — you cannot PATCH/DELETE them; those routes operate on stored documents via
findById. - Implicit relations are immutable through the API.
updateIdentifieris mandatory for safe updates. Omitting it skips the conflict check (the guard only fires when a differing value is supplied), so clients should round-trip the token.findAllcaps results at 500 and defaults to 100 — paginate for large tenants.- Mapping only writes
mapping.enabledtargets, andNever/Localdeliberately protect local edits; a value “not updating” is often the intended update-mode behavior, not a bug.
Behaviour history
Section titled “Behaviour history”- Adding a mapped or application-reference field required saving twice. The entity designer’s field list renders each item bound to a plain form control, but the mapped-field and application-reference-field dialogs used to insert a differently-shaped (nested) control — the new field appeared in the list, but a save did not pick up its value until something else re-wired it. Fixed by inserting the same plain-control shape the rest of the field list uses.
Platform 1.10.0 · Backend 1.11.0-alpha.11 · Frontend 1.11.0-alpha.6 · Mobile 1.10.2 · Chart 1.11.8 · Gateway 2.6.11 · MCP 0.2.0 · Grafana DS 1.2.0Docs build 2026-11-27