🚀 Welcome to MDriven Learn –  MDriven is now on Discord!  Don’t miss the latest Release Notes.
OnStateChange
This page was created by Lars.olofsson on 2020-09-06. Last edited by Wikiadmin on 2026-07-29.

You can use OnStateChange to record every state-machine trigger on an object, making it suitable for shared audit and logging behavior across all state machines on that class.

Use OnStateChange for cross-cutting state-change logging

OnStateChange is a specially named method with this signature:

OnStateChange(attrib:String; oldstate:String; newstate:String)

A class that has a method with this signature receives a call for each trigger call made on a state machine. The parameters identify:

Parameter Meaning
attrib The state-machine attribute involved in the trigger call.
oldstate The state before the trigger call.
newstate The state after the trigger call.

If a class has more than one state machine, calls from all of its state machines are routed through the same OnStateChange method. Use attrib to tell which state-machine attribute the event concerns.

Example: capture an audit record

For an object with state-machine attributes such as ApprovalState and DeliveryState, an audit entry can use the incoming values to describe the event:

  • attrib: ApprovalState
  • oldstate: Draft
  • newstate: Approved

The log can therefore identify that the object's approval state was triggered from Draft toward Approved, without placing equivalent logging logic in every individual state machine.

Do not use it to control transitions

OnStateChange is an event callback for observation, auditing, and logging. It is not the mechanism for preventing a transition. Put the rule that decides whether a transition is allowed in a state-machine guard.

For example, if an order must have a customer before it can move to an approved state, enforce that requirement with the transition guard. Use OnStateChange separately to record the trigger call for the approval state machine.

Choose the right location for state-related behavior

Need Use
Prevent a transition when a business condition is not met A state-machine guard
Perform behavior specific to entering a particular state or taking a particular transition A state effect or entry action
Record or handle state-machine trigger calls consistently across multiple state machines on the same class OnStateChange(attrib:String; oldstate:String; newstate:String)

Use state effects or entry actions when the behavior belongs to one state machine or one state. Use OnStateChange when the behavior is generic, such as centralized audit logging.

Related object lifecycle callbacks

OnStateChange concerns state-machine triggers. Other specially named callbacks cover object lifecycle events:

  • OnCreate runs after a new object has been created.
  • OnUpdate runs just before an object is saved to the database.
  • OnDelete runs when an object is deleted.

See also