2

still learning the apex ropes I've created a trigger which should create a contact after a custom object (School_bookings__c) record is created. My code is as follows:

trigger CreateSchoolContact on School_Booking__c (after insert) {

      List <Contact> ct = new List <Contact>();


for (School_Booking__c acc : Trigger.new) {


    // here is where you check if School_Booking__c that is being inserted
    //meets the criteria
    if (acc.Use_School_Contacts__c = true) {  

    Contact c = new Contact (); //instantiate the object to put values for future contact record

    // now map School_Booking__c fields to new vehicle object that is being created with this opportunity

    c.LastName = acc.Trip_Contact_Last_Name__c;
    c.FirstName = acc.Trip_Contact_First_Name__c;
    //c.Email = emailStringX;
    c.MobilePhone = acc.Trip_Contact_Number__c;
    c.xsms__Mobile_Phone_Country__c = 'Japan';
    c.Country__c = 'Japan';

    //once done, you need to add this new object to the list that would be later inserted. 

    ct.add(c);


    }//end if

}//end for o

//once loop is done, you need to insert new records in SF
//dml operations might cause an error, so you need to catch it with try/catch block.
try {
    insert ct;  
} catch (system.Dmlexception e) {
    system.debug(e);
}

 }

I keep getting this error:

 CreateSchoolContact: execution of AfterInsert caused by: System.FinalException: Record is read-only: 

Not sure what to do about this because the requirement is that I have the contact has to be created after the School_Booking__c has been created. Also is there a way to make a trigger only work after a workflow has updated certain fields?

Any help would be much appreciated.

5

In Apex Code, we use == for comparison, while = is for assignment. This means that you're actually trying to assign a value (true) to a field (acc.Use_School_Contacts__c). The system allows this syntax because you can perform an assignment and then use the result of that assignment later. However, in after insert and after update triggers, Trigger.new is read-only and cannot be modified in any way.

As a general rule, do not compare Boolean values to either true or false, because a Boolean value is already true or false. Checkbox fields are already a Boolean value that you can use directly.

if(acc.Use_School_Contacts__c)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.