Actions, validation and workflows
Vox-owned entities are changed through actions rather than unrestricted JSON updates. An action describes an intent—such as changing a product name, scheduling a campaign or closing a market—and its handler decides whether that intent is valid and how it changes the entity.
For the team workflow, see Change data together.
For ordinary editable properties, Vox generates create, update and delete actions from the entity model. Applications add custom actions where a change represents a business operation or has rules that a generic field editor cannot express.
Generated and custom actions
The generated actions make straightforward editing inexpensive. Each owned property, or object of owned
properties, gets an update action, eg SetName or SetPricing, and a locally owned index-backed relation gets
set, add and remove actions. Imported and system-owned relations have no local edit actions. Attributes can replace
those defaults with custom commands or remove deletion entirely.
An object is set as a whole only when its fields are all owned, in the same
permission scope and with the same
data classifications. Otherwise it's set through its parts, so that
each action needs one set of permissions and saving one field never replaces another the user can't change or read:
an object with calculated fields gets SetAvailabilityMerchandisingMessage for its owned message, and a Sourcing
object with a sensitive purchase price gets SetSourcingSupplier, SetSourcingLeadTimeDays and
SetSourcingPurchasePrice instead of SetSourcing. So marking a field in an object sensitive, or giving it another
scope, changes the object's default actions, which breaks API clients and Excel workbooks that call the old action.
A campaign lifecycle is a good example. Scheduling is one operation even though it changes dates and status together:
[Display(Name = "Schedule campaign")]
[VoxConfirmation("Schedule this campaign with the selected interval?")]
public class ScheduleCampaign : IVoxUpdate<Campaign>
{
public required DateTime StartsAtUtc { get; set; }
public required DateTime EndsAtUtc { get; set; }
}
Its handler receives both the command and the current entity. It can reject an invalid transition, change several
owned fields, change relations and append an entity-log entry as one atomic change. An action doesn't declare the
fields it changes: Vox compares the entity before and after, rejects a change of an imported or calculated field, and
requires the permission scopes of the fields that changed. [VoxUpdateRelations]
declares the index-backed relations an action may mutate. Each must be locally owned: the attribute does not grant
permission to change an imported or system-owned relation. Relation ownership follows the nearest ownership attribute
on the relation or its containing objects, with the same defaults as fields; see
Changing an index-backed relation.
Custom create and delete commands use the same model. [VoxCreatedBy], [VoxUpdatedBy] and [VoxDeletedBy] connect
an entity to the commands that own those operations. [VoxNoDelete] declares that deletion is not part of the
entity's lifecycle.
The generated create command has an optional Id: one that's left out is generated, see
the ids of new entities. A custom create handler may choose the id
itself, eg from the command, and Vox keeps it, or leave it empty for Vox to generate. When the entity type is
[VoxRequireId], the generated command's Id is required, a custom create command must have the id as a string
property named Id, and its handler must return the entity with that id. The id is checked before the handler runs,
so a missing or blank id fails with a validation error at id without side effects.
Values a new entity starts with
IVoxCreateDefaults<TEntity> fills in a create form before anyone types, eg the brand of a new product for a brand
manager. Vox creates a new entity of the type, lets the hook set its properties, and returns the fields of the create
action that the hook changed. The admin UI's create screen, and creating an entity from a reference list, start with
them as ordinary values: the person sees Acme already chosen, can change it, and the save is authorized as usual.
// Products start in the person's brand, when they manage exactly one
public class ProductCreateDefaults : IVoxCreateDefaults<Product>
{
public async Task SetDefaultsAsync(Product product, VoxCreateDefaultsContext context, CancellationToken cancellationToken)
{
var brands = await context.GetOwnContextIdsAsync<Brand>(cancellationToken);
if (brands.Count == 1)
{
product.Merchandising.Brand = new VoxReference<Brand>(brands.Single());
}
}
}
The context has the principal, the create action, the contexts the request selected, and GetOwnContextIdsAsync, the
principal's own contexts of a context type: the ones that its
grants limited to its own contexts apply in, read in
published content without the selection. With grants like that, a new product without a brand, or with someone
else's, is refused, so starting the form in the person's brand saves them a pick and an error.
GET api/{entityType}/actions/Create/defaults returns the values, eg { "values": { "brand": { "id": "acme" } } },
with ?kind= for a kind of an entity family. It needs the create permission, also if only in some contexts. A field with
a data classification the caller may not read is left out.
- Defaults pre-fill forms only. A create through the API that leaves a field out doesn't get its default: a value the server must always set belongs in a create handler, which runs on every create but isn't shown in the form.
- An entity type has at most one, implemented for its own class. The hook of an entity family gets an instance of the kind being created, so it can check the kind; one implemented for a kind's class is a model error.
- Only the default create action has defaults. A custom create command's fields aren't the entity's properties.
- Hooks are found in the scanned assemblies, or in
VoxOptions.Types, and resolved from the service provider, so they can depend on other services. It runs each time a create form opens, so keep it to a few reads.
Validation at different levels
Vox validates the complete candidate entity before saving it, whichever action produced it. Validation has three complementary levels:
- Data annotations describe local constraints such as required values, ranges and string lengths.
IVoxValidator<TEntity>implements rules that need the complete entity, its previous version or other data.- An action handler rejects an operation whose meaning is invalid in the current state.
For example, a campaign validator can check that the start precedes the end and that newly selected markets exist.
The lifecycle handler can separately reject an attempt to activate a campaign without products or a discount. The
first rule is true of every campaign version; the second belongs specifically to the activation operation. When
a campaign's products are an index-backed relation, the handler counts them with CountAsync instead of
loading them.
External entities are not validated by Vox because their source system owns their truth. Import handlers can still validate an incoming payload or reject an import, but Vox does not reinterpret the source's entity as locally owned.
Uniqueness
[VoxUnique] defines a database-backed uniqueness rule for a property or a combination of property paths:
[VoxUnique(nameof(Name), nameof(City), Name = "NameInCity")]
public class Store : IVoxEntity
{
public required string Name { get; set; }
public required string City { get; set; }
}
String comparisons ignore case by default. Drafts may temporarily conflict with published content while they are being prepared, but the rule is enforced when a version is published.
Validation checks only the unique values that a change gives the entity compared with its published version: a rename of a product that keeps its slug doesn't look up the slug again, and a change of the Swedish slug in one market checks only that market and language. The published values are already unique in the database, and the unique index stays the final guarantee against concurrent writes.
Concurrency and atomicity
Every update is based on a version. A stale command fails when a part it changes has moved on, rather than silently overwriting another editor's work. The owned, imported and calculated fields have independent revisions, so an action isn't stopped by a concurrent import or calculation. See Owned and mirrored data.
A client can submit several actions in order and have Vox save them as one change. Either every action and relation mutation succeeds, or none does. This lets a metadata-driven editor keep small, meaningful commands while presenting one Save button for a larger form.
Actions use the same save targets as other Vox-owned changes. They can publish immediately, update an ordinary draft, or contribute a version to a content release. Validation and business rules run before any of those versions is stored. A batch can also update the ordinary draft and publish it in the same change, eg for a form's "Save and publish": the draft's validation and the publication's, eg uniqueness in published content, both run before anything is stored. See Save and publish as one change.
Effects outside the entity
A handler's changes to the entity, its relations and its log are saved together, or not at all. Anything else a
handler does, eg changing an Accumulator balance, asking another system for a file or
saving another entity through IVoxEntityUpdater outside a transaction, happens when it runs,
whatever becomes of the save. Two things to design for:
- A handler can run more than once. When the save meets a newer version of the entity, eg an editor saved the same gift card a moment earlier, Vox runs the action again on the newest version, handler included. So key an effect outside the entity by the request, eg the order number, and when the handler finds its own earlier effect, treat it as done rather than as an error. Eg a gift card's balance handler finds that a redemption that's already applied but not yet in the card's log is the action's own, and completes.
- Authorization finishes after the handler. Vox checks the action's permission before it runs the handler, but a grant's scope, eg "gift cards in Norway", is checked against the entity the handler returns. A principal whose scope doesn't cover the change is refused after the effect has happened.
An effect that must not happen unless the change is saved belongs in an update side effect,
IVoxEntityUpdateSideEffect<TEntity> (see Calculations), which runs once the saved
change is published.
Why actions matter
The action model keeps domain decisions out of controllers and user interfaces. The Admin UI, another application and an automated agent can all discover the same commands and validation metadata, but none needs to duplicate the rules that make a change valid.
That shared command boundary is especially important when many purpose-built or AI-generated applications operate on the same domain. Each interface can shape the workflow for its audience without creating a local version of the business rules or a less governed path for changing the same data.
See Drafts and publishing, Users, roles and permissions and Editor metadata and selections.