0

Want to sync the User object to get sync with custom object with a trigger on "User". There is a field of Lookup(with User object) type in my Custom object(Employee__c) named as "user" Like if i create or update a user a new custom object(Employee__c) record get created or updated respectively. below is the fields of my Custom object(Employee__c) Fieldsenter image description here of my Custom object(Employee__c)

I have started with this but got lost . It Would be great if get the right trigger for this.

trigger SyncUserToEmployee on User (before insert , after update) {

     Set<String> existingemails = new Set<String>();
    Set<Id> existingids = new Set<Id>();

For(User usr : Trigger.new){

    existingemails.add(usr.Email);

}
Employee__c emp = new employee__c();
for(String email : existingemails ){

    emp.Email_Id__c = email;
    emp.Phone_Number__c = [select Phone from User where Email == email]

}


}

1 Answer 1

1

A simpler approach than using a trigger is to use formula fields. Those values will always be correct whatever updates or deletes are done to either User or Employee__c. (Covering all the cases requires quite a lot of trigger code.)

The (text) formulas on Employee__c would be User__r.Email for Email_Id__c and User__r.Phone for Phone_Number__c.

(Probably best not to include "Id" in a field name that does not hold an ID type value.)

PS

For a trigger solution, this (untested) trigger will propagate a change made on User to Employee__c:

trigger SyncUserToEmployee on User (after update) {

    Map<Id, User> m = the Map<Id, User>();
    for (User u : Trigger.new) {
        User old = Trigger.oldMap.get(u.Id);
        if (old.Email != u.Email || old.Phone != u.Phone) m.put(u.Id, u);
    }

    if (m.size() > 0) {
        Employee__c[] es = [
                select User__c
                from Employee__c
                where User__c in :m.keySet()
                ];
        for (Employee__c e : es) {
            User u = m.get(e.User__c);
            e.Email_Id__c = u.Email;
            e.Phone_Number__c = u.Phone;
        }
        update es;
    }
}

but there will also need to be a trigger on Employee__c to handle the initial User__c lookup assignment and any changes to that.

Note that this trigger is relying on the User__c lookup field to relate the objects not just the Email value.

4
  • Thanks , Keith . I am looking for applying trigger only for this functionality. If you can help with this functionality it would be great.
    – Sfdcnewbie
    May 1, 2016 at 16:53
  • @Sfdcnewbie Why?
    – Keith C
    May 1, 2016 at 16:58
  • Lol.. lets say want to learn
    – Sfdcnewbie
    May 1, 2016 at 17:01
  • @Sfdcnewbie I've added some trigger code.
    – Keith C
    May 1, 2016 at 17:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .