Saturday, November 10, 2018

Mixed DML Error in Apex in Salesforce.com

Mixed DML Error 
Concept of Mixed DML error is to prevent transaction from incorrect user level access in the org.
Mixed DML error occurs when you try to insert or update the setup and non setup object records simultaneously.
To overcome from this restriction you need to insert or update setup and non setup object records separately, where one method must be implementing @future keyword.

Note:- This restriction exists because some sObjects affect the user's access to records in the org.

e.g. you can’t update an account and a user role in a single transaction but deleting has no restriction.

These fields of user object can not be updated
* Username
* ProfileId
* UserRoleId
* IsActive
* ForecastEnabled
* IsPortalEnabled

ApexCode1A

public class MixedDMLClass {
    public static void createAccountAndUser () {
        // First DML operation
        Account account = new Account(Name='Acme');
        insert account;
       
        // Second DML operation (insert a user with a role) can't be mixed with              // the previous insert unless it is within a future method.
        // Call future method to insert a user with a role.
        CreateUserUtil.insertUserWithRole(
           'allen','allenAs', 'allen@gmail.com', 'paul'
           );       

    }
}

ApexCode1B

public class CreateUserUtil {
    @future
    public static void insertUserWithRole(String uname, String alias, String email, String lname){

        Profile std_profile = [Select Id From Profile Where Name='Standard User'];
        UserRole coo_role = [Select Id From UserRole Where Name='COO'];

        // Create new user with a non-null user role ID
        User user = new User(
lastname=lname,
username=uname,
profileid = std_profile .Id,
userroleid = coo_role.Id,
alias = alias,
email=email,
emailencodingkey='UTF-8',
languagelocalekey='en_US',
localesidkey='en_US',
timezonesidkey='America/Los_Angeles'
);

        insert user;
    }
}










No comments:

Post a Comment

Validation in flow input text field in sfdc: Maximum 255 characters limit

The input text field validate in sfdc flow behaves opposite of the generic sfdc validation rule.  Here the validation formula is evaluating ...