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
K_devK_dev 

Trigger to update Account field

Can anybody  check and tweak this trigger according to my requirement.
 

  Create a new read only field on Customer for "Latest Call List"  Text 30 (or whatever field length the call list name is).  Every time a call list object is added to Person Account, a trigger updates this field with the Call List name(whichever is the latest record).

 Call List is Master detail to Person Account.So whenever a new calllist is added immediately latest_Call_List__c field on account must be updated with the call list name.
trigger UpdatenameFieldstoAccount on call_list__c (after insert, after delete, after update)
{
    Set<String> accountIds = new Set<String>();
    
    if(Trigger.isDelete)
    {
        for( Call_List__c calllist : Trigger.old)
        {
            accountIds.add(calllist.Account__c);
        }
    }
    else
    {
        for(Call_List__c calllist : Trigger.new)
        {
            accountIds.add(calllist.Account__c);
        }
    }
    
    List<Account> accounts = new List<Account>();
    for(Account acc : [select latest_Call_List__c, (select Name from Call_List__r order by CreatedDate asc) from Account where Id in :accountIds])
    {
       acc.latest_Call_List__c = null;
        for(Call_List__c calllist : acc.call_List__r)
        {
       acc.latest_Call_List__c = calllist.Name;
        accounts.add(acc);
    }
    if(accounts.size() > 0)
    {
        update accounts;
    }
}