You're inadvertently trying to update every Account in your database, in addition to some other logical issues.
You do this:
List<Account> accs = new List <Account>([SELECT Id, Parent.Name,Parent_Account_for_LAM__c FROM Account]);
and then you also do this:
update accs;
in a for
loop, no less. Since you're querying with no filters, you've just tried to update every Account in Salesforce, as many times over as there are Accounts in the trigger set. That will wipe out your allowed DML rows very quickly, and it's certainly not what you are intending to do.
What you seem to be aiming to do is query those Accounts that are in scope for your trigger so that you can access parent values. To do so, you'd need a filter on your query:
List<Account> accs = new List <Account>([
SELECT Id, Parent.Name,Parent_Account_for_LAM__c
FROM Account
WHERE Id IN :Trigger.newMap.keySet()
]);
Then, you would iterate over accs
(not Trigger.new
).
You'll probably also want to handle the case where multiple child Accounts of the same parent Account are being updated; the usual pattern is to accumulate updates not in a List<Account>
but a Map<Id, Account>
, and at the very end of your trigger do update myMap.values();
Failing to do so will land you an exception for duplicate values in the update list.
Your update code is also incorrect.
Account accounttoUpdate = new Account (Id = a.Id);
accounttoUpdate.Parent.Name = a.Parent_Account_for_LAM__r.Name;
accs.add(accounttoUpdate);
You cannot update related records in SOQL this way. Your accounttoUpdate
Id should be the Id of the parent, and you should populate the fields you want to update directly on that record. You also need to check whether the parent is present - i.e., is not null
- before you try to construct the updatable record.
Your trigger will recurse up the Account hierarchy, but I suspect that may be what you want here. The recursion should be naturally limited due to the maximum depth of the Account hierarchy, and should be further limited by "do I need to do work" checks like the Name
comparison you perform. You may also wish to check whether or not parent lookups themselves have changed prior to performing the query at all, but that's really a next-version upgrade once you get this working at all.