4

I am creating a SF community to allow contractual employees to access some of their information in our org. I am attempting to shift some accountability to these employees by making them responsible for ensuring their contact and shipping info is up-to-date without needing some case submission or approval process, but limiting what they can change heavily.

I've come across this trigger and class that did just this by synchronizing the fields in their portal profile with their internal contact record.

Source: https://developer.salesforce.com/page/Synchronizing_Portal_Users_with_Contact_Record_Data

Since communities have replaced Portals for the type of functionality I am looking for, will this trigger work similarly on a community profile given some tweaks?

I'm just beginning to learn Apex (and programming in general), so sorry if this should be relatively obvious.

5

It should work but u need to remove test method and put it in separate class.

Class

 global class UpdateContactFromCommunityUser { 
    @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; 
        }
    }

}

Trigger

 trigger UpdateContactFromCommunityUser 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) { 
            UpdateContactFromCommunityUser.updateContacts(u.Id); 
        } 
    } 
}

Test Class

@isTest 
private class UpdateContactTestClass {
  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); 
    }
}
| improve this answer | |
  • Thanks for the input! Would adapting this for community users be as simple as replacing the word "portal" with "community" in the trigger and classes? – JaredT Feb 25 '16 at 19:27
  • @jatuttle0 yes, updated the code..please check now – sfdc Feb 25 '16 at 19:31
  • Fantastic. I'm waiting for my sandbox to refresh so I'll test it asap. Thanks again! – JaredT Feb 25 '16 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.