function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mazlow Cohen 12Mazlow Cohen 12 

I need to write a trigger to update a field(Field A) on record(Object A) After Insert and After Update with a value from a field(Field B) on its Parent(Object B). The relationship is master detail

I am trying to write a trigger to update a field(Field_A) on record(Object_A) when Object_A is created or updated with the value from a field(Field_B) on its Parent(Object_B). The relationship is master detail. Object_B is the master.

 I want to make sure the code is bulkified. I am having a bit of trouble figuring it out. I know it should be simple. 

Any ideas on how to do this best?
William TranWilliam Tran
Is this an exercise where you want to learn trigger?  or is this a real scenario you want to solve. 

You can easily achieve this via Workflow, no need to write triggers.
Workfrow rule on Object A,

Workflow field update on Field A set equal to ObjectB.FieldB

Thx
sfdc550sfdc550
update child records when parent record is updated in Salesforce
 
trigger ContactUpdate on Account (after insert, after update) {
    set<Id> acctIds = new set<Id>();
    map<Id, Account> mapAccount = new map<Id, Account>();
    list<Contact> listContact = new list<Contact>();
    
    for(Account acct : trigger.new) {
        acctIds.add(acct.Id);
        mapAccount.put(acct.Id, acct);
    }
    
    listContact = [SELECT MailingStreet, MailingCity, AccountId FROM Contact WHERE AccountId IN : acctIds];
    
    if(listContact.size() > 0) {
        for(Contact con : listContact) {
            con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;
            con.MailingCity = mapAccount.get(con.AccountId).BillingCity;
        }
        update listContact;
    }
}

Cheers!!!

Whenever billingstreet is updated in accounts related contacts mailingstreet will be updated.
Prashant WayalPrashant Wayal
Hi Mazlow,

If I understand your requirment correctly, then you are trying to update your child record field value with parent record field value, right?

If this is the case, then instead of writing the trigger and wasting your time, just create the formula field on child object(Object_A) as below:

Field_A = Object_B__r.Field_B

Here, wherever you link the child record with it's parent record, Field_A will automatically updated with the value of Field_B from it's parent object.


Thanks,
Prashant
Mazlow Cohen 12Mazlow Cohen 12
I am having trouble doing this. I am trying to put the Account Name into a custom text field called "Household Name Text" on the child Contact whenever a contact is created or the Parent Household changes.

Do you know how I can do this?