Populate Lookup Field with Record Created From Tri

2019-08-01 20:37发布

问题:

I am trying to create a trigger that does the following:

  1. Once an Account has been created, create an unrelated record (called a "Portal Content" record) that bears the same name, assuming the default RecordTypeId
  2. Take the ID of the newly created "Portal Content" record, and insert it into a lookup field on the originally created Account

My current code does item 1 successfully, but when I added new code to complete item 2, I received the following error:

Line: 6, Column: 1
System.DmlException: Insert failed. First exception on row 0; first error: 
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, newAccountCreated: execution of 
AfterInsert caused by: System.FinalException: Record is read-only 
Trigger.newAccountCreated: line 12, column 1: []

My current trigger is as follows:

trigger newAccountCreated on Account (after insert) {

    List<Account> alist = Trigger.New;

    for(Account a : alist) {

        if (a.RecordTypeId == '012i0000001Iy1H') {
//            system.debug(a.Name);
            Portal_Content__c p = new Portal_Content__c(Name=a.Name,School_SFDC_ID__c=a.Id);
            insert p;

            a.Portal_Content_Record__c = p.Id;
            update a;
        }
    }

}

I do not understand why the the error message states that the "Record is read only," or how to amend this error.

回答1:

You cannot update the same record on an 'after' trigger, it must be done on a before trigger; change to:

trigger newAccountCreated on Account (before insert) {