+ Start a Discussion
ECoronaECorona 

Trigger Update related record with lookup field priorvalue

Hello, we have two objects A and B, in A we have a lookup field that, when it changes, update a text field in B, at this point we are working ok, but when the lookup field on A change, the record on B is not updated to edit the information on the text field, do you have any idea on how to do this???

I'll really appreciate your help.
Best Answer chosen by ECorona
Khan AnasKhan Anas (Salesforce Developers) 
Hi ECorona,

Below is the sample code which I have tested in my org and it is working fine.

BookMaster__c is Lookup field in Test__c Object.
trigger UpdateOnLookupChange on Test__c (before insert, before update) {
    
    List<ID> OppIds = New List<ID>();
    Map<Id,Book__c> promap = new Map<Id,Book__c>();
    
    for(Test__c o : Trigger.new){
        OppIds.add(o.BookMaster__c);
    }
    
    promap = new Map<Id, Book__c>([SELECT id, Name FROM Book__c WHERE ID IN :OppIds]);
    
    for(Test__c c : Trigger.new) {
        if(c.BookMaster__c != null) {
            Book__c b = promap.get(c.BookMaster__c);
            b.Name='Khan';
        }
    }
    
    update promap.values();
}

I hope it helps you.

Kindly let me inform if it helps you and close your query by marking it as solved so that it can help others in future.

Thanks and Regards,
Khan Anas

 

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi ECorona,

Below is the sample code which I have tested in my org and it is working fine.

BookMaster__c is Lookup field in Test__c Object.
trigger UpdateOnLookupChange on Test__c (before insert, before update) {
    
    List<ID> OppIds = New List<ID>();
    Map<Id,Book__c> promap = new Map<Id,Book__c>();
    
    for(Test__c o : Trigger.new){
        OppIds.add(o.BookMaster__c);
    }
    
    promap = new Map<Id, Book__c>([SELECT id, Name FROM Book__c WHERE ID IN :OppIds]);
    
    for(Test__c c : Trigger.new) {
        if(c.BookMaster__c != null) {
            Book__c b = promap.get(c.BookMaster__c);
            b.Name='Khan';
        }
    }
    
    update promap.values();
}

I hope it helps you.

Kindly let me inform if it helps you and close your query by marking it as solved so that it can help others in future.

Thanks and Regards,
Khan Anas

 
This was selected as the best answer
ECoronaECorona
Thank you Khan, It helped us a lot!!!