Saturday, 18 January 2014

"Setup" objects and "Non-setup" objects in SFDC

There are two types of objects that you can interact with on the platform. One is "setup" object and the other is a "non-setup" object.
A "setup" object is one that must be edited from the setup or builder area of the platform.

 Setup objects are

* User

* RecordType

* Profile

 etc

and all other general objects i.e.

* Contact

* Account

* Lead

etc

are the None setup objects.

If you run a DML operation on setup object you can't run a DML operation on None setup object in the same context, it will show the "Mixed_DML_operation" error.


For example, you cannot insert an account and then insert a user or a group member in a single transaction.

Salesforce don’t allow you to run.

 Solving MIXED_DML_OPERATION exception in Apex

Sometimes there is a need to update a Setup Object and a non-setup Custom object in Apex on the same event. It can get really tricky if the operation is needed on 2 Setup Objects instead 1. The solution lies in using RunAs function in Apex and putting one of the operation in @future construct. As an example, the following code is not expected to work-
...
User testuser = [Select id, isActive from User where isActive=true Limit 1];
testuser.isActive = false;
update testuser;
CustomObject__c co = new CustomObject__c(name='Test object');
insert co;
...
and this should be re-written as -
...
@future
function updateUser() {
User testuser = [Select id, isActive from User where isActive=true Limit 1];
testuser.isActive = false;
update testuser;
}
...
[MainMethod]
...
RunAs(<user>) {
Test.startTest();
updateUser();
Test.stopTest();
}
CustomObject__c co = new CustomObject__c(name='Test object');
insert co;



No comments:

Post a Comment