0

Once a custom record is created by a Community user on the Napili Community, Account lookup field of that record should be populated from UserID(CreatedBy) >> ContactId >> AccountID. I am trying to update a Lookup field of a record after its creation using a trigger.

trigger setAccountLookup on Kindle__c (after insert) {
Kindle__c[] resList = new Kindle__c[] {};
   for (Kindle__c res : Trigger.new){
       res.Account__c = res.CreatedBy.Contact.AccountId;
       resList.add(res);
   }
   update resList;
}

ERROR: setAccountLookup: execution of AfterInsert caused by: System.FinalException: Record is read-only Trigger.setAccountLookup: line 4, column 1

Am I missing something or doing it in the wrong way?

1

1 Answer 1

3

The Apex Developer Guide clearly recommends you perform field updates in a before context:

Triggers

...

There are two types of triggers:

  • Before triggers are used to update or validate record values before they’re saved to the database.
  • After triggers are used to access field values that are set by the system (such as a record's Id or LastModifiedDate field), and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue. The records that fire the after trigger are read-only.

Note, however, that you cannot access parent fields of trigger context records. You must query for them. Since you are firing this logic on the insert event, you can assume CreatedById will correspond with the running user, so you should be able to query for just the running user.

User runningUser = [SELECT Contact.AccountId FROM User WHERE Id = :UserInfo.getUserId()];
for (MyObject__c record : trigger.new)
{
    record.Account__c = runningUser.Contact.AccountId;
}
3
  • 1
    To be pedantic, this logic is not strictly applicable, because administrators can now enable create audit fields without intervention from support. ☺
    – sfdcfox
    Aug 30, 2017 at 1:15
  • Yes I considered that scenario, but it doesn't seem especially relevant here. Also somewhat peripheral to the main problem.
    – Adrian Larson
    Aug 30, 2017 at 1:17
  • @AdrianLarson Sounds good. I might not be able to follow you guys on what you discussed in the above comments, but, I understood what I need to do to make my use-case work. Its good to see you both commenting on my question :)
    – Arnold Jr.
    Aug 30, 2017 at 1:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .