Tuesday, September 27, 2016

State Machines in CRM for Status Transitions

Those who come more from an engineering background might be familiar with the concept of state machines. This article explains an easy implementation in CRM.

State machines are basically a way to model an object’s life cycle, including the different states or statuses it can have along with the transitions that are possible to go from one state to another. In an example below we have an airline ticket and how the status of the ticket can transition in different scenarios:

The key about state machines is that it restricts invalid state changes. For example, you cannot go from “Used” to “paid” because once the ticket is used, it can no longer change. In some sate machines you might also want to specify which states are read-only as opposed to “editable” and you can even define additional conditions such as having the correct privilege (e.g. only a manager is able to issue a refund).

Now you can apply this concept of state machines to CRM entities. Although these state machines can be quite complex in real life, in CRM entities most of the times this is not too complex. If you have a simple state machine to model, there is the feature in CRM (often overlooked) called status transitions.

You can actually define which status can lead to which status. Below is the CRM implementation of the state machine of my example:

Note that CRM requires that for each “Active” status you must have defined a valid transition to an “inactive” state (at least this is mentioned in the documentation here: https://technet.microsoft.com/en-us/library/dn660979.aspx although I’m not sure where it is enforced if it is).

Now in the CRM form you will notice that it will remove the invalid state transitions from the available status reasons. For example, if my record is on status reason “Reserved” I cannot change it to “Ticketed” because I need to mark it as paid first:

If I had not defined a transition from the current status reason to an “Inactive” state then I am not able to de-activate the record and change the state to “Inactive”:

Also note that the transition validations are valid even outside the scope of CRM forms. If you try to perform an invalid status update from workflow/plugin/SDK you would get this error:

    Entity: new_airplaneticket does not have valid status code

No comments:

Post a Comment