Trying to learn Apex, walking through Trailhead. Here is description and then my attempt, getting this error: "Error: DML statment cannot operate on trigger.new or trigger.old: Trigger.AccountAddressTrigger: line 7, column 1"


Create an Apex trigger for Account that matches Shipping Address Postal Code with Billing Address Postal Code based on a custom field.
For this challenge, you need to create a trigger that, before insert or update, checks for a checkbox, and if the checkbox field is true, sets the Shipping Postal Code (whose API name is ShippingPostalCode) to be the same as the Billing Postal Code (BillingPostalCode).
The Apex trigger must be called 'AccountAddressTrigger'.
The Account object will need a new custom checkbox that should have the Field Label 'Match Billing Address' and Field Name of 'Match_Billing_Address'. The resulting API Name should be 'Match_Billing_Address__c'.
With 'AccountAddressTrigger' active, if an Account has a Billing Postal Code and 'Match_Billing_Address__c' is true, the record should have the Shipping Postal Code set to match on insert or update.

My attempt:

trigger AccountAddressTrigger on Account (before insert, before update) {
    for ( Account a : Trigger.new ) {
        if ( a.BillingPostalCode != NULL && a.Match_Billing_Address__c == true )
            a.shippingPostalCode = a.billingpostalcode;
        update a;

1 Answer 1


"Before insert" and "before update" triggers allow you to modify the incoming data before it's committed to the database. Therefore, there's no need to actually call update on the record(s) in the trigger, because they'll automatically be committed with whatever data your trigger sets in those fields (subject to standard validation).

  • Thanks, so does that mean I should delete "update a;" ? Sep 18, 2015 at 21:27
  • ....and it works! Challenge completed, 500 trailhead points! thanks man Sep 18, 2015 at 21:28
  • @TNSalesforceGuru All I did was nudge you in the right direction. I'd recommend spending some more time reading the documentation... It'll come with practice.
    – sfdcfox
    Sep 18, 2015 at 21:29

You must log in to answer this question.

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