Quickstart: Synchronizing Portal Users with Contact Record Data

Available in: Salesforce Classic

This is part of Developing with the Service Cloud.

Use Case

Customer Portal users have the ability to edit some information about themselves via the My Profile page. That page allows them to edit their own User record, but not their own Contact or Account record. However, the User record does have some fields in common with Contact and Account, and with a quick bit of Apex, you can make it such that when the portal user updates his information, that gets reflected in his Contact or Account record as well.

Sample Code: Trigger that synchronizes User data to Contact data

This trigger synchronizes the Contact and User object by calling an @future method on the class defined below it.

trigger UpdateContactFromPortalUser on User (after update) {
    //We only want to run on the single item that the user edited 
    if (Trigger.new.size()==1) 
    { 
        User u =_ Trigger.new[0]; 
        //And only if it's a portal user 
        if (u.ContactId!=null) { 
            UpdateContactFromPortalUser.updateContacts(u.Id); 
        } 
    } 
}

Sample Code: Class that synchronizes User data to Contact data

global class UpdateContactFromPortalUser { 
    @future 
    public static void updateContacts(String userId) {
        User u = [select ContactId,Email,FirstName,LastName,Title
                    from User
                    where Id=:userId];

        if (u!=null && u.ContactId!=null) {
            Contact c = new Contact(Id=u.ContactId,Email=u.Email,FirstName=u.FirstName,LastName=u.LastName,Title=u.Title);
            update c; 
        }
    }

    static testMethod void testUpdateContacts() {
        Test.startTest(); 
        User u = [select Id,ContactId,FirstName from User where ContactId<>'' limit 1]; 

        u.FirstName='Bar'; 
        update u; 

        Test.stopTest(); 

        Contact c = [select FirstName from Contact where Id=:u.ContactId]; 
        System.assertEquals(c.FirstName,u.FirstName); 
    }
}