Screenplay nested objects: manage optional read-model data
A Screenplay nested block maintains one optional object inside a read model. Use it when the parent can exist without that object, such as a slice with no configured command. A from event creates or updates the object; clear with sets it back to null without deleting the parent.
Unlike children, a nested object has no separate collection identity. It occupies one property on its containing read model. The examples below follow a slice’s optional command through configuration, updates, and clearing.
Basic Syntax
Section titled “Basic Syntax”nested {PropertyName} from {SetEvent} clear with {ClearEvent}Simple Example
Section titled “Simple Example”projection Slice => SliceReadModel from SliceCreated Name = name
nested command from CommandSetForSlice Name = commandName Schema = schema clear with CommandClearedForSliceDeclare command as a nullable object property on SliceReadModel. SliceCreated supplies the parent name; CommandSetForSlice fills the command’s Name and Schema. After CommandClearedForSlice, the slice still exists, but its command is null.
These events must resolve to the same slice instance. The fragments use the default event source identity; see Keys when the slice ID comes from an event field instead.
From Event
Section titled “From Event”Mappings inside nested target the nested object’s fields. Here Name means the command’s name, not the slice’s name. You can map those fields explicitly or use auto-map for matching names:
nested command from CommandSetForSlice Name = commandName Schema = schema Rules = validationRulesClear With
Section titled “Clear With”Choose a clearing event when the object has a meaningful absent state. Removing a command configuration leaves the slice available without it:
nested command from CommandSetForSlice clear with CommandClearedForSliceCommandClearedForSlice clears the whole command object, including its schema and any other fields. A later nested from event can create it again.
To keep the object but clear one field, use a clear <property> mapping line inside from. See Property Mapping for that separate operation.
Multiple From Events
Section titled “Multiple From Events”Give each event the mappings for what it changes. A rename can leave the command schema intact, and a schema update can leave the name intact:
nested command from CommandSetForSlice Name = commandName Schema = schema
from CommandRenamed Name = newName
from CommandSchemaUpdated Schema = updatedSchema
clear with CommandClearedForSliceLater events merge their mapped fields into the existing object rather than replacing it. Any nested from event can also create the object if it is absent. If a rename must only occur after configuration, express that requirement in the command’s rules; declaring it as a nested from does not make it update-only.
With AutoMap
Section titled “With AutoMap”Use nested-level automap when event fields already have the names expected by the command object:
nested command automap
from CommandSetForSlice from CommandUpdated clear with CommandClearedForSliceEvery Block in Nested
Section titled “Every Block in Nested”Put every inside nested when a shared mapping belongs on that object. The command’s modification time can be set alongside each of its from mappings:
nested command every LastModified = $eventContext.occurred
from CommandSetForSlice Name = commandName Schema = schema
from CommandUpdated Schema = updatedSchema
clear with CommandClearedForSliceIn Chronicle, LastModified is stored on the command when its from events are applied. Screenplay’s reference evaluator does not support $eventContext.occurred mappings inside nested objects, so it cannot execute this timestamp example.
Clearing the command also removes its timestamp. Keep an audit timestamp on the parent if it must remain visible while the command is absent.
Nested Within Nested
Section titled “Nested Within Nested”The command can itself have an optional validation object. Clearing validation leaves the command in place; clearing the command removes the entire command value, including validation:
nested command from CommandSetForSlice Name = commandName
nested validation from ValidationConfigured Rules = rules clear with ValidationRemoved
clear with CommandClearedForSliceNested Within Children
Section titled “Nested Within Children”A collection element can hold an optional object too. Here each task can have one assignee value without making assignees another collection.
The assignment and clearing events below omit both child and parent keys, so both default to event source identity. This shorthand only reaches the intended task when those identities coincide. With separate task and project IDs, declare the assignment as from TaskAssigned key taskId with parent projectId. Clearing can use a keyed remove with inside the nested block when it also needs explicit child and parent keys:
children tasks identified by taskId from TaskAdded key taskId parent projectId Title = title
nested assignee from TaskAssigned Name = assigneeName Email = assigneeEmail clear with TaskUnassignedRead Model Structure
Section titled “Read Model Structure”The read model declares the nested property as a nullable complex type: one object with its own fields. In the command example, those fields include Name and Schema. Its initial value is null; nested from mappings populate it, and clear with restores that absent state.
Root-level nested objects can also contain joins, including within further nested objects. Chronicle 19.99.1 supports those joins, as does Screenplay’s reference evaluator with the backfill difference described on the joins page. Joins in nested objects under children, collections inside nested objects, and remove via join inside nested objects are not supported. Required fields populated only by a nested join still trigger the compiler’s PLAY0284 population check.
Examples
Section titled “Examples”Slice with Optional Command
Section titled “Slice with Optional Command”This version uses matching fields for initial configuration and keeps the rename mapping explicit because newName differs from Name:
projection Slice => SliceReadModel from SliceCreated Name = name
nested command automap
from CommandSetForSlice from CommandRenamed Name = newName
clear with CommandClearedForSliceEmployee with Optional Active Contract
Section titled “Employee with Optional Active Contract”The same shape suits a current contract. An extension changes only the end date; ending the contract clears the optional value while retaining the employee:
projection Employee => EmployeeReadModel from EmployeeHired Name = name Department = department
nested activeContract from ContractStarted ContractId = contractId StartDate = startDate EndDate = endDate Type = contractType
from ContractExtended EndDate = newEndDate
clear with ContractEndedProduct with Optional Promotion
Section titled “Product with Optional Promotion”A product’s base price belongs on the parent because it remains when the promotion is removed. Promotion fields belong in the optional object:
projection Product => ProductReadModel from ProductListed Name = name BasePrice = price
nested promotion from PromotionApplied Label = promotionName DiscountPercent = discount ValidUntil = expiresAt
clear with PromotionRemovedBest Practices
Section titled “Best Practices”Choose nested when one property can be present or absent as a whole. Choose children when the parent holds several independently identified items. Clearing a nested value is not deletion of the parent, and it does not preserve a populated object with an inactive flag.
In executable specifications, check initial absence, a partial update that preserves other fields, clearing, and recreation. Pay particular attention to events such as renames: every nested from is allowed to create the object, so its mappings must make sense when no earlier value exists.
See Also
Section titled “See Also”- Children - Use a collection when each item needs its own identity.
- From Event - Choose mappings for the events that populate the object.
- Auto-Map - Use matching names instead of explicit field mappings.
- Removal - Remove a root instance rather than clearing one of its properties.