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
AnbuAnbu 

Custom field automatically filled with some text

Hello guys,

In case object I have a lookup to account. I would like to write a trigger that fill a custom field e.g Account_Name__c, with the same value of the lookup but as text field. Could you help me with this? thanks!!
Bryan Leaman 6Bryan Leaman 6
I believe this could easily be done in a workflow to set the value to the formula Account.Name.

However, to do it in a trigger would go something like this:
trigger myCaseTrigger on Case (before insert, before update) {
 
    // Collect set of all referenced account ids
    Set<Id> accountIds = new Set<Id>();
    for(Case c : Trigger.new) {
        if c.AccountId!=null accountIds.add(c.AccountId);
    }
 
    // Query all accounts at once to get the account names
    Map<Id,Account> accountMap = new Map<Id, Account>([
        select Id, Name from Account where Id in :accountIds
    ]);
 
    // Set the custom account name field to the referenced account name
    for(Case c : Trigger.new) {
        Account a = accountMap.get(c.AccountId);
        c.Account_Name__c = a!=null ? a.Name : null;
    }
 
}

I haven't tested the above, so there could easily be a typo or other bug -- ymmv.