Running Lead or Case assignment rules using APEX

Sure, you can run the Lead or Case assignment rules by creating a case or lead from within Salesforce. This is done by either having the rules run automatically on insert or maybe you choose to run them manually at a later time.

But wait! What if you need to run the rules after a lead or case has been created within the context of a trigger. Maybe because it has been created through the Salesforce API or you would like to have some custom logic as to when the rules will be run or even what rules to run (Ex. When the object is created with a particular field value or a particular field value has changed).

Salesforce makes this possible through the DML Options Class. The one caveat is this will need to be executed in an after trigger context.

The code snippet below shows how you can run the default assignment rules in an after insert trigger on the Lead object, the same can be done to run the default assignment rules on the Case object.

code-runassignmentrules

If you would like to run a specific assignment rule instead of the default, you can assign the assignmentRuleHeader to the Salesforce Id of the rule (Ex. dmo.assignmentRuleHeader = ‘xxxxxxxxxxxxxxx’).

For more information on this and other DML Options see the Salesforce DML Options Cass.


2 thoughts on “Running Lead or Case assignment rules using APEX

    1. Looking through our org, I don’t see a test for this specifically, but you should pretty easily be able to test this by just creating a Lead, inserting it and then querying for the Lead Owner to be what you would expect based on your assignment rules logic. So, if we were to just do some pseudo-code:

      Lead l = new Lead(FirstName = ‘test’, LastName=’test’, etc….);
      insert l;

      then, update your lead to meet new criteria,
      update l;

      Lead updatedLead = [Select Id, Name, OwnerId from Lead where Id = :l.Id];
      system.assert(updatedLead.OwnerId = whatever you expect the assignment rules to be set as);

      PLEASE BE AWARE THIS IS NOT FUNCTIONAL TESTS, this is only a place to start. You will need to fill in the logic on how your assignment rules should work.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s