Apex Triggers - Trailhead

10.9k Views Asked by At

The code itself doesn't give any errors, but anytime I run it Trailhead gives me this message:

"Challenge not yet complete... here's what's wrong: Executing the trigger did not work as expected. "

Here are the instructions:

For this challenge, you need to create a trigger that, before insert or update, checks for a checkbox. If the checkbox field is true, it 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 code:

trigger AccountAddressTrigger on Account (before insert,before update) {

    for(Account a : [SELECT Id FROM Account WHERE  Match_Billing_Address__c = TRUE AND BillingPostalCode != NULL])
    {
        a.ShippingPostalCode = a.BillingPostalCode;
        update a;        
    }//end for     
}
4

There are 4 best solutions below

0
On BEST ANSWER

Your Trigger is like this way.

trigger AccountAddressTrigger on Account (before insert,before update) {

    //Iterate all accounts that is updated or inserted.
    for(Account acc :Trigger.New){
        //if match is true set values.
        if(acc.Match_Billing_Address__c){
            acc.ShippingPostalCode = acc.BillingPostalCode;
        }
    }
}
1
On

trigger AccountAddressTrigger on Account (before insert,before update) {

    for(Account a : Trigger.new){
    If (a.Match_Billing_Address__c == true && a.BillingPostalCode!=Null) {
        a.ShippingPostalCode = a.BillingPostalCode;
    }   
} 

}

0
On

First need to create check box field with name Match billing address in Account tab then open developer console and write the code and save it .Finally check that whether its working or not again in ur salesforce instance

here is the code :

trigger accountAddressTrigger on Account (before insert, before update) {

for(Account acct : trigger.new){

      if(acct.Match_Billing_Address__c == true)

      acct.ShippingPostalCode = acct.BillingPostalCode;
      }

}

0
On

Trigger Name_of_Trigger on Object (Event 1,Event 2) {

   for(Each Object's Event1/Event2) {
       if (Check box is selected) {
               Assign Billing address to Shipping address (i.e using '=' operator);
                                 }
                      }

}