function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Wei Dong 10Wei Dong 10 

How to update User.username?

I have a RESTful API that lets me update something.

Since this is an External User (A user is automatically created with a Personal Account). I wanna know why I cannot update User's username? If I update this, there'll be the error occuring:

10:38:10:978 USER_DEBUG [283]|DEBUG|=== User Updated Error ===Update failed. First exception on row 0 with id 0030m00000IztRaAAJ; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Account, original object: User: []

Here're the codes:
 
public static CA_RSEUserResponse updateUserInfo(CA_RSEUserInfo rseUserInfo) {

    User u = null;
    CA_RSEUserResponse resp = new CA_RSEUserResponse();
    Savepoint sv = Database.setSavepoint();

    try {
        // 1. Update User
        u = [
                SELECT Username,Email,FirstName,LastName,Id,ContactId
                FROM User
                WHERE Id = :rseUserInfo.id
                LIMIT 1
        ];

        System.debug('=== User ID is ===' + rseUserInfo.id);
        System.debug('User Contact ID is ===' + u.ContactId);

        u.Username = rseUserInfo.email_address;
        u.Email = rseUserInfo.email_address;
        u.FirstName = rseUserInfo.first_name;
        u.LastName = rseUserInfo.last_name;
        update u;


        // 2. Find the related contact and fill in the info
        Contact foundContact = [
                SELECT LastName,FirstName,Birthdate,MailingCity,MailingState,
                        MailingPostalCode,Phone,CA_Subscription_Status__c,CA_Gender__c,
                        CA_Dependants__c,CA_SkillLevel__c,CA_FavoriteCuisines__c,
                        CA_RecipeDislikes__c,CA_RecipeLikes__c,CA_Retailer__c,
                        CA_LanguagePreference__c,CA_EnjoymentLevel__c,CA_RepeatFrequency__c,
                        CA_AdventureLevel__c,CA_CreatedProfile__c,CA_CompletedProfile__c,
                        CA_HouseholdAdults__c
                FROM Contact
                WHERE Id = :u.ContactId
                LIMIT 1
        ];

        System.debug('Birth Year ==='+rseUserInfo.birth_year);

        foundContact.LastName = rseUserInfo.last_name;
        foundContact.FirstName = rseUserInfo.first_name;
        foundContact.Birthdate = rseUserInfo.birth_year;
        foundContact.MailingCity = rseUserInfo.city;
        foundContact.MailingState = rseUserInfo.state;
        foundContact.MailingPostalCode = rseUserInfo.zip;
        foundContact.Phone = rseUserInfo.mobile_phone;
        foundContact.CA_Subscription_Status__c = rseUserInfo.subscription_status;
        foundContact.CA_Gender__c = rseUserInfo.gender;
        foundContact.CA_Dependants__c = rseUserInfo.dependants;
        foundContact.CA_SkillLevel__c = rseUserInfo.skill_level;
        foundContact.CA_FavoriteCuisines__c = rseUserInfo.favorite_cuisines;
        foundContact.CA_RecipeDislikes__c = rseUserInfo.recipe_dislikes;
        foundContact.CA_RecipeLikes__c = rseUserInfo.recipe_favorites;
        foundContact.CA_Retailer__c = rseUserInfo.retailer;
        foundContact.CA_LanguagePreference__c = rseUserInfo.language_preference;
        foundContact.CA_EnjoymentLevel__c = rseUserInfo.enjoyment_level;
        foundContact.CA_RepeatFrequency__c = rseUserInfo.repeat_frequency;
        foundContact.CA_AdventureLevel__c = rseUserInfo.adventure_level;
        foundContact.CA_CreatedProfile__c = rseUserInfo.created_profile;
        foundContact.CA_CompletedProfile__c = rseUserInfo.completed_profile;
        foundContact.CA_HouseholdAdults__c = rseUserInfo.household_adults;
        update foundContact;

        resp.errorMsg = null;
        resp.content = rseUserInfo;
    } catch (Exception ex) {
        Database.rollback(sv);
        System.debug('=== User Updated Error ===' + ex.getMessage());
        rseUserInfo = null;
    }

    return resp;
If I remove 'User.username = xxx' for update, everything is good……so why and how to update that?
Deepali KulshresthaDeepali Kulshrestha
Hi Wei,

If we perform DML operation on the standard/custom object and global objects(User, UserRole, Group, GroupMember, Permission Set, etc...) in the same transaction this error will come.
To avoid this error, we should perform DML operation on standard/custom object records in a different transaction.

In general, all the apex classes and apex triggers execute synchronously (execute immediately).
If we perform DML operation on standard/custom object records asynchronously (execute in future context), we can avoid MIXED-DML-OPERATION error.

For more information on how to avoid the mix DML operation error. Please refer to these links:

http://www.sfdcpanda.com/avoiding-mixed-dml-operations-exception-example/
http://www.salesforceadda.com/2017/08/future-method-and-prevent-mixed-dml.html
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dml_non_mix_sobjects_test_methods.htm

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha 
Wei Dong 10Wei Dong 10
Hi,

Sorry I did what you told me but nothing works with me……:(
 
//Notice:'_rseUserInfo' is a static private variable in the class range

@Future
    private static void updateContact(Id contactID) {

        //3. Update all the info
        Contact foundContact = [
                SELECT LastName,FirstName,Birthdate,MailingCity,MailingState,
                        MailingPostalCode,Phone,CA_Subscription_Status__c,CA_Gender__c,
                        CA_Dependants__c,CA_SkillLevel__c,CA_FavoriteCuisines__c,
                        CA_RecipeDislikes__c,CA_RecipeLikes__c,CA_Retailer__c,
                        CA_LanguagePreference__c,CA_EnjoymentLevel__c,CA_RepeatFrequency__c,
                        CA_AdventureLevel__c,CA_CreatedProfile__c,CA_CompletedProfile__c,
                        CA_HouseholdAdults__c
                FROM Contact
                WHERE Id = :contactID
                LIMIT 1
        ];


        foundContact.Email = _rseUserInfo.email_address;
        foundContact.LastName = _rseUserInfo.last_name;
        foundContact.FirstName = _rseUserInfo.first_name;
        foundContact.Birthdate = _rseUserInfo.birth_year;
        foundContact.MailingCity = _rseUserInfo.city;
        foundContact.MailingState = _rseUserInfo.state;
        foundContact.MailingPostalCode = _rseUserInfo.zip;
        foundContact.Phone = _rseUserInfo.mobile_phone;
        foundContact.CA_Subscription_Status__c = _rseUserInfo.subscription_status;
        foundContact.CA_Gender__c = _rseUserInfo.gender;
        foundContact.CA_Dependants__c = _rseUserInfo.dependants;
        foundContact.CA_SkillLevel__c = _rseUserInfo.skill_level;
        foundContact.CA_FavoriteCuisines__c = _rseUserInfo.favorite_cuisines;
        foundContact.CA_RecipeDislikes__c = _rseUserInfo.recipe_dislikes;
        foundContact.CA_RecipeLikes__c = _rseUserInfo.recipe_favorites;
        foundContact.CA_Retailer__c = _rseUserInfo.retailer;
        foundContact.CA_LanguagePreference__c = _rseUserInfo.language_preference;
        foundContact.CA_EnjoymentLevel__c = _rseUserInfo.enjoyment_level;
        foundContact.CA_RepeatFrequency__c = _rseUserInfo.repeat_frequency;
        foundContact.CA_AdventureLevel__c = _rseUserInfo.adventure_level;
        foundContact.CA_CreatedProfile__c = _rseUserInfo.created_profile;
        foundContact.CA_CompletedProfile__c = _rseUserInfo.completed_profile;
        foundContact.CA_HouseholdAdults__c = _rseUserInfo.household_adults;
        update foundContact;
    }

    /**
     * Update the userInfo by email address
     * @return the updated (latest) userInfo.
     * If there's anything wrong with the User when updating, an error
     * will occur.
     */
    public static CA_RSEUserResponse updateUserInfo(CA_RSEUserInfo rseUserInfo) {

        User u = null;
        CA_RSEUserResponse resp = new CA_RSEUserResponse();
        Savepoint sv = Database.setSavepoint();

        try {

            // 1. Update User
            u = [
                    SELECT Username,Email,FirstName,LastName,ContactId
                    FROM User
                    WHERE Id = :rseUserInfo.id
                    LIMIT 1
            ];

            System.debug('=== User ID is ===' + rseUserInfo.id);
            System.debug('User Contact ID is ===' + u.ContactId);

            u.Username = rseUserInfo.email_address;
            u.Email = rseUserInfo.email_address;
            u.FirstName = rseUserInfo.first_name;
            u.LastName = rseUserInfo.last_name;
            update u;

            _rseUserInfo = rseUserInfo;

            updateContact(u.ContactId);

            resp.errorMsg = null;
            resp.content = rseUserInfo;
        } catch (Exception ex) {
            Database.rollback(sv);
            System.debug('=== User Updated Error ===' + ex.getMessage());
            resp.errorMsg = ex.getMessage();
        }

        return resp;
    }