Based on Option Set Auto Number Prefix Change Using Plugins

Based on Option Set Auto Number Prefix Change Using Plugins

Auto numbering is commonly used in Dynamics 365 to generate unique identifiers for records. However, many business scenarios require different numbering prefixes based on record categories or business types.

Using plugins, Dynamics 365 developers can dynamically generate auto numbers based on Option Set values, making records easier to identify, track, and manage.

Business Requirement

Suppose an Option Set field named Category contains the following values:

The generated numbers should follow:

CUST-0001
VEND-0001
EMP-0001
PROJ-0001

Why Use Plugins for Auto Numbering?

Plugin Registration

Register the plugin on the Create message of the target table.

Message:
Create

Stage:
Pre-Operation

Mode:
Synchronous

Retrieve Option Set Value

OptionSetValue category =
entity.GetAttributeValue(
"new_category");

int categoryValue =
category.Value;

Determine Prefix

string prefix = "";

switch(categoryValue)
{
   case 100000000:
      prefix = "CUST";
      break;

   case 100000001:
      prefix = "VEND";
      break;

   case 100000002:
      prefix = "EMP";
      break;

   case 100000003:
      prefix = "PROJ";
      break;
}

Generate Auto Number

string autoNumber =
prefix + "-" +
sequenceNumber.ToString("0000");

entity["new_autonumber"] =
autoNumber;

Sample Output

Customer → CUST-0001
Vendor → VEND-0001
Employee → EMP-0001
Project → PROJ-0001 Important: Store sequence numbers in a dedicated configuration table to prevent duplicate numbering when multiple users create records simultaneously.

Implementation Steps

  1. Create the Option Set field.
  2. Create an Auto Number field.
  3. Develop the plugin in C#.
  4. Retrieve the Option Set value.
  5. Generate the appropriate prefix.
  6. Create the sequence number.
  7. Populate the Auto Number field.
  8. Register and test the plugin.

Common Use Cases

Benefits

Key Takeaways