Tuesday, March 15, 2016

Developer: Tackling MIXED_DML_OPERATION, on setup object is not permitted error..

A common need in most organizations is a need to create Contact records when a User is created.

If you try to implement such a requirement synchronously then you end up with the following
error:

MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object

Solution

The error occurs because User is treated as a setup object by Salesforce and Contact is not.

@ future methods are a way of implementing asynchronous operations like webservice callouts.

Following is a sample of how you would start your code:
public with sharing class CreateUsrContact { 
 @future public static void CreateUsrContact (List<String> UsrId){ 

  system.debug('UsrId' + UsrId);
....Complete code as desired....
}}

There are also limitations in terms of what types of data can and cannot be passed as parameters...for e.g Sobject cannot be passed in.

Call this code from an after update User trigger for our example will prevent the clash from happening and will solve the error.

@ future methods also come with their own set of governor limitations that you need to be familiar with when designing solutions.

No more than 50 invocations per APEX code and also no more than
200* number of licenses in a 24 hr period.


No comments:

Post a Comment