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
Pri TaunkPri Taunk 

Apex trigger to update a custom field on the account object based on the custom object line items


I'm trying to write a trigger to update a custom text field on the account object based on the line items (Name field) from a custom object that's linked to the account object. I want the values on the custom text field to be updated as an when line items are added / edited to the custom object or  even deleted. 
I'm quite new to apex so any guidance will be helpful, thanks
Leonardi KohLeonardi Koh
For more information on basic trigger:

And a rough framework for such trigger:
trigger MyTrigger on MyCustomObject__c (after insert, after update, before delete) {

    Map<Id, String> mapOfAccountToUpdate = new Map<Id, String>();
    for (MyCustomObject__c obj : Trigger.New) {
        if (Trigger.isDelete) {
            mapOfAccountToUpdate.put(obj.AccountLookupField__c, '');
        } else {
            mapOfAccountToUpdate.put(obj.AccountLookupField__c, obj.Name);

    List<Account> accountsToUpdate = new List<Account>();
    for (Id accountId : mapOfAccountToUpdate.keySet()) {
         Account newAccountToUpdate = new Account();
         newAccountToUpdate.Id = accountId;
         newAccountToUpdate.MyCustomTextField__c = mapOfAccountToUpdate.get(accountId);

    if (!accountToUpdate.isEmpty()) update accountsToUpdate;
Note, this is just a rough work of the basic trigger and is just a quick sample of how one might do it, normally we'd have handler class for proper trigger logic implementation segregation but that's more complex than is necessary here.
Pri TaunkPri Taunk
Thanks for this guidance Leonardi, I'm going to give this a try :)