Shreyas
Shreyas

Reputation: 1

How to auto-populate parent field with a lookup field value from child

There is a text field Editor__c in Account object and lookup field User__c in Contact object. As soon as I select a value from User__c lookup field and save it the same value should be automatically updated in the Editor__c field if the profile is of Editor

I tried with flows and trigger but couldn’t find any solution

Upvotes: 0

Views: 173

Answers (1)

eyescream
eyescream

Reputation: 19637

Collect the ids in 1 loop. Check if they're right profile. Loop again and update accounts. You'll have to think what should happen if somebody updates 2 contacts at same time, which value should win.

trigger HiStack on Contact(after update){
Set<Id> candidates = new Set<Id>();
for(Contact c : trigger.new){
    Contact old = trigger.oldMap.get(c.Id);
    if(c.User__c != old.User__c && c.User__c != null){
        candidates.add(c.User__c);
    }
}
if(!candidates.isEmpty()){
    Map<Id, User> editors = new Map<Id, User>([SELECT Id FROM User WHERE Id IN :candidates AND Profile.Name = 'Editor']);
    Map<Id, Account> accountsToUpdate = new Map<Id, Account>();
    if(!editors.isEmpty()){
        for(Contact c : trigger.new){
            if(c.User__c != old.User__c && editors.containsKey(c.Id)){
                accountsToUpdate.put(c.AccountId, new Account(Id = c.AccountId, Editor__c = c.User__c));
        }
        update accountsToUpdate.values();
    }
}

}

Upvotes: 0

Related Questions