0

If we are creating or updating Contact with account then we need to fill custom field on it Account_LastName(I've created this field on my org) this field should be filled with related Account Name + his Id. In case if we are changing account name this should also be reflected in that field Here is what i did for now: Trigger:

trigger ContTrigRoma on Contact(before insert, before update){
    
    if(Trigger.isBefore && Trigger.isInsert){
        TriggerHandler.handlerForRoma(Trigger.new);
    } else if (Trigger.isBefore && Trigger.isUpdate) {
        
    }
}

Handler:

public with sharing class TriggerHandler {
    public static void handlerForRoma(List<Contact> contacts){
        for (Contact cont : contacts) {
            if(cont.AccountId != null){
                cont.Account_LastName__c = cont.AccountId + cont.Account.Name;
            }
        }
        insert contacts;
    }
}

For some reason i can't even test it by creating contact object because i get an error : DML statement cannot operate on trigger.new or trigger.old

2 Answers 2

1

You don't need to perform DML when modifying Trigger.new; any changes you make will automatically be committed to the database. Remove the insert contacts; statement.

You can't reference parent or child objects directly from Trigger.new. You need to query for those records, as demonstrated in this question, and as mentioned in my blog post, The Aggregate Query Update Pattern.

Your final code should look like:

public static void handlerForRoma(List<Contact> contacts){
    Map<Id, Account> accounts = new Map<Id, Account>();
    for(Contact record: contacts) {
        accounts.put(record.AccountId, null);
    }
    accounts.putAll([SELECT Name FROM Account WHERE Id = :accounts.keySet()]);
    for(Contact record: contacts) {
        Account parent = accounts.get(record.AccountId);
        if(parent != null) {
            record.Account_LastName__c = record.AccountId + parent.Name;
        }
    }
}
1
  • To clarify for others: This only works when you're in a before trigger, and you must modify the instances of the records in trigger.new. If you write a query like List<Contact> conList = [SELECT Id FROM Contact WHERE Id IN :Trigger.new]; and then modify the record instances in conList, the automatic update behavior of before triggers won't happen.
    – Derek F
    Jan 27, 2021 at 13:32
1

Just adding 1 point to sfdcfox comment- you can simply achieve this by created formula field on the contact that will reference the account.name. You can/should use it in case the Account_LastName should not be changed manually on the contact level to other value then the accont name.

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.