0

A Community User is trying to create a record in a Custom Object, this trigger autofills the account lookup and the account owner is made this custom object owner as well.

Object Level Permission, Account - Public Read Only & Custom Object - Public Read/Write

Without this trigger I am able to create records for that Custom Object but if I try to create a record with this trigger Active - I get an error as

"Error: Invalid Data. Review all error messages below to correct your data. Apex trigger AutofillFields caused an unexpected exception, contact your administrator: AutofillFields: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.AutofillFields: line 12, column 1"

trigger AutofillFields on MyCustomObject__c (After Insert,After Update) {

    List<User> lstUser = [Select Id, ContactID, Contact.AccountID, Contact.Account.OwnerID, Profile.Name FROM User 
                            WHERE Profile.Name LIKE 'Customer Community Name'];

    for(User iusr : lstUser){
        For(MyCustomObject__c irow : Trigger.new){
            IF(UserInfo.getUserId().contains(iusr.ID)){ 
                irow.Account__c = iusr.Contact.AccountID;
                irow.OwnerID = iusr.Contact.Account.OwnerID;                
            }
        }
    }
}
2
  • I cannot have Master Detail Relation between Account and this Custom Object so had to go with Lookup Relationship, Please help me out with this issue.
    – SFDev
    Aug 31, 2015 at 9:54
  • 1
    Why don't you use a before trigger?
    – tugce
    Aug 31, 2015 at 11:15

1 Answer 1

1

Per the SF Documentation

You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers, trigger.new is not saved, so a runtime exception is thrown.

You are attempting to make a change to trigger.new, hence the exception. You have a few options when you have an error like this

  • Use a before trigger, where you can make changes to trigger.new as it has not yet been saved.
  • If you want to use an after trigger, you must first query the records you want to update, and make changes to that collection and use DML to save that collection.

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