+ Start a Discussion
DannyK89DannyK89 

Trigger creating a record

I would like to create a trigger that creates a record. I have created a wizard where an outside user creates a record. I would like a trigger to run when the user saves the record they created through the wizard. I would like the trigger to search a different objects records for similar email adresses. After doing that if no similar addresses are found I want the trigger to create a new record. Here is what I have so far.  Here is the error that I get:

 

Apex trigger ReferralTrigger caused an unexpected exception, contact your administrator: ReferralTrigger: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.ReferralTrigger: line 22, column 17

 

 

trigger ReferralTrigger on Referral__c (after insert, after update) {
    
    List<Referee__c> Ree = [SELECT Referee_Email__c, Name, Id FROM Referee__c];
    Referee__c newRee = new Referee__c();
    Boolean add = false;
    
        for(Referral__c Rf : trigger.new){
            for(Referee__c Re : Ree){
                if(Rf.Your_Email__c != Re.Referee_Email__c || Re == null) add = true;
            }
        }
        if(add == true){
            for(Referral__c Ref : trigger.new){
                newRee.Name = Ref.Your_Name__c;
                newRee.Referee_Email__c = Ref.Your_Email__c;
                newRee.Referee_Phone__c = Ref.Your_Cell_Phone__c;
                newRee.Referee_City__c = Ref.Your_City__c;
                newRee.Referee_State__c = Ref.Your_State__c;
        
                insert newRee;
            
                Ref.Referee__c = newRee.Id; 
            }
        }
}

 

 

sylar20sylar20

try to keep it before update..

Ritesh AswaneyRitesh Aswaney

I'd agree with Sylar - since you're attempting to modify the records which caused the trigger to fire, this is best done in a before insert, before update trigger, than than an after trigger.

sfdcfoxsfdcfox

More to the point, before triggers are used to update the data before it goes into the database. Once committed (i.e. you are in the after commit events), you can not update the records either in Trigger.new or by using a DML operation on them until the operation has fully completed. After triggers are usually written when you need to create or update related records after all validation of the user input has completed.