• Dennis Morris 18
  • NEWBIE
  • 10 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
Hey Everyone,
New to APEX here and I'm trying to update records on the same Object which the Before Update and Before Insert trigger is fired.
Basically, I have a Communication Method object which stores email addresses.  When an email address is stored or updated with the same type (Work, Personal, Other) and it is marked as as Roll Up = true, any records with the same type associated with the Contact should be updated with Roll Up = false.  I'm using this Roll Up field to roll these values up to the Contact to three specific fields (Not covered in this code).
I wrote the following:
trigger ComMethRollup on Communication_Method__c (after insert, after update) {

    if(checkRecursive.runOnce())
    {
//Pull together List of Object Records 
    List<Communication_Method__c> allComMeth = new List <Communication_Method__c>();
    for (Communication_Method__c newComMeth: Trigger.new) {
//Query for Parent Contact and fields associated with Communication Method Record
	List<Contact> conList = [SELECT Home_Email__c,Other_Email__c,Work_Email__c from Contact WHERE Id = :newComMeth.Name__c];
	Contact assoContact = conList.get(0);
//Query for all Communication Method Records associated with the Contact with same type
	List<Communication_Method__c> assoMeth = [SELECT Id,Email__c,Roll_Up__c,Type__c from Communication_Method__c WHERE Name__c = :assoContact.ID AND Type__c = :newComMeth.Type__c];
        for (Communication_Method__c c: assoMeth)
//Check if new Communication Method record has rollup checked
        if (newComMeth.Roll_Up__c = TRUE) {
            c.Roll_Up__c = FALSE;
        	}
         UPDATE assoMeth;   
   		}
    
	}
}

and then got a dreaded
 Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger ComMethRollup caused an unexpected exception, contact your administrator: ComMethRollup: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.ComMethRollup: line 15, column 1

I then found an article (https://help.salesforce.com/HTViewSolution?id=000133752&language=en_US) to create a Static Boolean check class and refer to this at the start of my trigger.
I did do this, but am getting the same error.
Any help would be appreciated.
Thanks!