function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AVINASH UPADHYAAVINASH UPADHYA 

Apex Triggers

Hi All,

Can anyone please help me with bellow challenge.


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.

For above challenge i tried with following code but looks like it doesnt mach the requirement.

trigger AccountAddressTrigger on Account (before insert, before update) {
    for(Account a : Trigger.new){
        If (a.Match_Billing_Address__c = true) {
            /*ShippingPostalCode = BillingPostalCode;*/
        }   
    } 

}

Please help me
Best Answer chosen by AVINASH UPADHYA
@anilbathula@@anilbathula@
Hi AVINASH,

Try this code:-
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;
        }   
    } 

}

Thanks
Anil.B

All Answers

@anilbathula@@anilbathula@
Hi AVINASH,

Try this code:-
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;
        }   
    } 

}

Thanks
Anil.B
This was selected as the best answer
AVINASH UPADHYAAVINASH UPADHYA
Thanks Anil for helping me to resolve. But i have got one quick question!

In your code a.ShippingPostalCode means ShippingPostalCode is a field from Account Std. object right? If so when i check the fields(Setup --> Customize --> Accounts --> Fields) i couldnt find ShippingPostalCode in the list of fields. Can you please help me to find the list of fields for Accounts Std objects!

Thanks in advance
Chidambar ReddyChidambar Reddy
Hi Avinash,

You can find list of apex available fields from the developer console

Open Developer Console > File > Open > Objects > double click on Account

Thanks
Ghanshyam Yadav01Ghanshyam Yadav01
This code is also working fine

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

for(Account a : Trigger.new){
if(a.Match_Billing_Address__c = True)
a.ShippingPostalCode = a.BillingPostalCode;
}
}



Regards,
Ghanshyam
Kabi StolovitsKabi Stolovits

a.Match_Billing_Address__c = True should be a.Match_Billing_Address__c == True 
Niket KediaNiket Kedia

Hi I tried Anil's code and the error is:


Error: Compile Error: Variable does not exist: ShippingPostalCode at line 5 column 13

Rida Akhtar 9Rida Akhtar 9
Please try this .It is working:

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

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

After puttinhg the code.Go to accounts tab,pick up any record and edit.

set TRUE to  Match_Billing_Address__c ,fill both BillingPostalCode, ShippingPostalCode with some different text.Click Save.

Now see the text of BillingPostalCode and ShippingPostalCode is same.
 

Satyanarayana PusuluriSatyanarayana Pusuluri
Hi,

It's working with below code

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;
        }   
    } 

}
Vikas MishraVikas Mishra
First create a custom field 
Setup->customize->Accounts->fields->Custom fields and relationships 
Select custom field --> field type (Checkbox) and enter name as "Match Billing Address" , checkbox (checked) 
Save.
Now write the below code, it is working without any errors

trigger AccountAddressTrigger on Account (before insert, before update) {
    for (Account a: Trigger.new)
    {
        if(a.Match_Billing_Address__c==True)
        {
            a.ShippingPostalCode=a.BillingPostalCode;
        }
    }
}
Mandodari RawatMandodari Rawat
@Vikas you didn't check the condition  if an Account has a value in Billing Postal Code or not.
trigger AccountAddressTrigger on Account (before insert, before update) {
	for(Account act : Trigger.new){
		If(act.Match_Billing_Address__c == true && act.BillingPostalCode!= null){
			act.ShippingPostalCode=act.BillingPostalCode;
		}
	}
}
Below is the alternate If condition in which we can check both fields Match_Billing_Address__c and BillingPostalCode must have a value to get the
ShippingPostalCode updated..
If(act.Match_Billing_Address__c && act.BillingPostalCode!= null)
Ashraful Islam 19Ashraful Islam 19
@Vikas It's not working until you not uncheck the checkbox field.
 
Select custom field --> field type (Checkbox) and enter name as "Match Billing Address" , checkbox (checked)

 
Prashant ShelarPrashant Shelar
@Mandodari Rawat excellant...it works
Anurag PareekAnurag Pareek
Hey All,

Its working fine for me :-
 
trigger AccountAddressTrigger on Account (before insert, before update) {

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

}

 
Sean KetchamSean Ketcham
Is anyone getting this error?

Challenge Not yet complete... here's what's wrong: 
Setting 'Match_Billing_Address__c' to false updated the records anyway. The trigger should only act when Match_Billing_Address__c is true.
Virender Singh 8Virender Singh 8
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;
        }   
    } 

}
sfuser12sfuser12
This one is the right answer
Try it.. it works..  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'. Create this custom field and it should be unchecked while creating this custom field.

trigger AccountAddressTrigger on Account (before insert, before update)
{
    for(Account a : Trigger.new)
    {
        If (a.Match_Billing_Address__c == true)
        {
            a.ShippingPostalCode = a.BillingPostalCode;

        }  
    }
}
Tagg2020Tagg2020
Hi,

Anil's IF conditions are the most solid, there is just a typo in the a.Match_Billing_Address__c = true.

One = sign is trying to assign the value of true, but this can't be done in a conditional. You need to use two == to represent a comparison:

 
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;
		}
	}

}

 
Verma, ManishVerma, Manish
Hi,

You can use code below to solve your problem:
 
trigger AccountAddressTrigger on Account (before insert, before update) {

	for (Account acc : Trigger.new) {
		if(acc.BillingPostalCode != null && acc.Match_Billing_Address__c == true){
			acc.ShippingPostalCode = acc.BillingPostalCode;
		}
	}
}

Hope this helps!!
Ajmer Singh 5Ajmer Singh 5
i use the above codes... something happens...
when i update the billing postal code then it works...
but when i update the shipping postal code then it doesn't work.
anybody tell me..
Ajmer Singh 5Ajmer Singh 5
okk .. i got it..
RupeshKumarRupeshKumar

Hi, It might sound silly but why did we use

 for (Account acc : Trigger.new)
and why not 
for (Account acc : Trigger.old) ?

I am asking this because I tried with and the latter and got stuck for half an hour. 

Appreciate if anyone clarifies, Thanks in advance! :)

Surya Prakash TomarSurya Prakash Tomar
hi rupesh 
if u work on new account so go for Trigger.new
and trigger.old we are used for old account..
Fnu SumitFnu Sumit
in best answer use '==' for first true then it will work fine
 
Alaa AliAlaa Ali
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;
        }   
    } 

}
Brooks Bruce 43Brooks Bruce 43
I'm getting some beahvior I can't explain. I have the same code as above and it works great for the instructions. However, in playing around with it, I've noticed that once I've checked the Matching Billing Address checkbox, completed the Billing Zip, and saved, whenever I uncheck the Match Billing Address checkbox and save, it automatically re-checks the Match Billing Address checkbox; why?

Also, once I've checked the Match Account Billing checkbox, completed the Billing Zip field, and saved, if I go back in and delete the Billing Zip but leave the Match Billing Address checkbox checked, when I save it automatically unchecks the Match Account Billing checkbox; why?

Thanks for your time and help.

Best,
Brooks
Navin Dayama 2Navin Dayama 2

Trigger Coding :- Challenge 1
trigger AccountAddressTrigger on Account (before insert, before update)
{
   for(Account a : Trigger.new){
        If (a.Match_Billing_Address__c == true) {
            a.ShippingPostalCode = a.BillingPostalCode;
        }   
    } 
}
Ghanshyam Choudhari 9Ghanshyam Choudhari 9
// 100% Bullet Proof Trigger
trigger AccountAddressTrigger on Account (before insert , before update) {
    for(Account acc:Trigger.New){
        if(acc.Match_Billing_Address__c && (acc.BillingPostalCode != null || acc.BillingPostalCode!=' ' )){
           acc.ShippingPostalCode = acc.BillingPostalCode;
        }
    }
}
  • Used acc.Match_Billing_Address__c instead of acc.Match_Billing_Address__c==True because acc.Match_Billing_Address__c is checkbox field so it either hold True or False if it is True then only it will go into the if block.
  • Used acc.BillingPostalCode != null because Null is an absence of a value. 
  • Used acc.BillingPostalCode!='  '  Empty string is a value, but is just empty.
Jess BurghJess Burgh
Hey all! Still trying to figure this challenge out. I created the "Checkbox" account object and then wrote out my code in my developer console and getting the message that the field I created is an invalid field match. What am I doing wrong? Help!! User-added image
Safdar MirzaSafdar Mirza
Why this error?
--->Error: Compile Error: Invalid field Match_Billing_Address__c for SObject Account at line 3 column 4

Thats my code:

trigger AccountAddressTrigger on Account (before insert,before update) {
for(Account a : Trigger.new){
if(a.Match_Billing_Address__c = True)
a.ShippingPostalCode = a.BillingPostalCode;
}
}
 
NerdyNerdy
Hello,
did anyone get this error ?!

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AddRelatedRecord: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Discount_Percent__c, Discount_Percent_Status__c]: [Discount_Percent__c, Discount_Percent_Status__c] Trigger.AddRelatedRecord: line 23, column 1: []


Here is my code ( i already created the custom checkbox )

trigger AccountAddressTrigger on Account (before insert, before update) {
    for (Account act: Trigger.new)
    {
        if(act.Match_Billing_Address__c==True)
        {
            act.ShippingPostalCode=act.BillingPostalCode;
        }
    }
Jamie AxtellJamie Axtell
Hi there!  I was attempting to change the username in Account New Sales for an Account when I received this error message:

Error: Apex trigger ParentTrigger caused an unexpected exception, contact your administrator: ParentTrigger: execution of AfterUpdate

caused by: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_ACCESS_LEVEL, (ACC_SHARE.ACC_ACCESS_LEVEL, ACC_SHARE.OPP_ACCESS_LEVEL, ACC_SHARE.CASE_ACCESS_LEVEL, ACC_SHARE.CON_ACCESS_LEVEL) (Account, Opportunity, Case Levels, Con Levels (Read, Read, Edit, Read) are below organization levels (Edit, Edit, Edit, ControlledByParent)): []: Class.Accountsharingtrigger.recordshare: line 12, column 1

Got a fix for this?
Kim Young HwanKim Young Hwan
Hello

in best answer
a.Match_Billing_Address__c = true  
a.Match_Billing_Address__c == true
xuer zoxuer zo
After a few trial, i figured out that ShippingPostalCode cannot be null to pass this test,here is what i did to make it work:
trigger AccountAddressTrigger on Account (before insert, before update) {
    for (Account a : Trigger.new) {
        if (a.ShippingPostalCode == null) {
            a.ShippingPostalCode = ' ';
        }        
        if (a.Match_Billing_Address__c==true && a.BillingPostalCode != null) {
            a.ShippingPostalCode = a.BillingPostalCode;
            system.debug('shipping postal code is ' + a.ShippingPostalCode + 'Billing postal code ' + a.BillingPostalCode);
        }

    }
}
Ajeeth Kumar SAjeeth Kumar S
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;
        } 
    }

}
 
Santosh Babu PadisalaSantosh Babu Padisala
trigger AccountAddressTrigger on Account (before insert , before update) {
    for(Account acc:Trigger.New){
        if(acc.Match_Billing_Address__c && (acc.BillingPostalCode != null || acc.BillingPostalCode!=' ' )){
         acc.ShippingPostalCode = acc.BillingPostalCode;
        }
    }
}
Amit BehereAmit Behere
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;
        }   
    } 

}

 
Ilya IvanovskiyIlya Ivanovskiy
Create an Apex trigger for Account that matches Shipping Address Postal Code with Billing Address Postal Code based on a custom field.
 
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;
        }   
    } 
}
Ankit Jain 2909Ankit Jain 2909
trigger AccountAddressTrigger on Account (before insert, before update) {
    for(Account acc : Trigger.new) {
        If (acc.Match_Billing_Address__c = true && acc.BillingPostalCode!=Null) {
            acc.ShippingPostalCode = acc.BillingPostalCode;
        }   
    } 
}
Gajanan Nandawadekar 1Gajanan Nandawadekar 1
trigger AccountAddressTrigger on Account (before insert,before update) {
        
    
            for(Account ac:Trigger.new)
            {
                if(ac.Match_Billing_Address__c ==true && ac.BillingPostalCode!=Null)
                {
                    ac.ShippingPostalCode =ac.BillingPostalCode;                 
                }
                else{
                    ac.BillingPostalCode=ac.BillingPostalCode;
                }
                
            }
    
            
        
}
smriti sharan19smriti sharan19
trigger AccountAddressTrigger on Account(before insert, before update){

for (Account acc:Trigger.new){
    if(ac.Match_Billing_Address__c ==true && ac.BillingPostalCode!=Null)
                {
                    ac.ShippingPostalCode =ac.BillingPostalCode;                 
                }
}
}
Lokendra Pal Singh 6Lokendra Pal Singh 6
Create an Apex trigger for Account that matches Shipping Address Postal Code with Billing Address Postal Code based on a custom field.

This code works perfectly fine.

trigger AccountAddressTrigger on Account (before insert, before update)
     {
             for(Account acc:trigger.new)
                   {
                          if(acc.match_Billing_Address__c==True)
                                       {
                                                  acc.ShippingPostalCode = acc.BillingPostalCode;
                                         }
                       }
         }


#lopsact
VenkataRamanjaneyulu KattamuruVenkataRamanjaneyulu Kattamuru
Hi,

The following code is working fine for me.
 
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;
           }              
    }
}

Regars,
Venkat Kattamuru.
Prashanth MPrashanth M
Hi guys,
      
           Best answer chosen is almost correct as it is missing '=' symbol,

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;
        }   
    } 

}



 
suvarna Reddysuvarna Reddy
hi avinash
suvarna Reddysuvarna Reddy
how to write using metadata type and display user role  modifify which button available
Prashant Singh 166Prashant Singh 166
Getting below error while creating trigger as below;
trigger AccountAddressTrigger on Account (before insert, before update)
{
    for(Account a : Trigger.new)
    {
        If (a.Match_Billing_Address__c == true)
        {
            a.ShippingPostalCode = a.BillingPostalCode;

        }  
    }
}
Error Message:
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [First_Name__c, Last_Name__c]: [First_Name__c, Last_Name__c]
Harsh Raj Choudhary 2Harsh Raj Choudhary 2
/*
Module: Apex Triggers
Sub Module: Get Started with Apex Triggers
Link: https://trailhead.salesforce.com/content/learn/modules/apex_triggers/apex_triggers_intro
*/

trigger AccountAddressTrigger on Account (before insert, before update) {
    for(Account accObj: Trigger.new){
        if(accObj.Match_Billing_Address__c && String.isNotBlank(String.valueOf(accObj.BillingPostalCode))){
            accObj.ShippingPostalCode  = accObj.BillingPostalCode;
        }
    }
}

you will be able to get all the fields name from developer console by follwing below steps
Open Developer Console > File > Open > Objects > double click on Account

Thanks


The longer answer is that the ShippingPostalCode / BillingPostalCode field is a part of BillingAddress'compound' field (introduced in API v30.0, aka the Spring '14 release), which has a bunch of limitations which are outlined in the documentation on compound fields. One of those limitations is that compound fields are read-only. If you want to set values for an address, you need to set values for the individual fields (e.g. BillingStreet, BillingCity, BillingPostalCode, etc...)
Personally, I've attempted to use compound fields in the past, but found it to be more trouble than it was worth.

Thanks
Sravan Baratam 3Sravan Baratam 3
Try this code .



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;
        }  
    }
}
 
sandeep salawadgi 8sandeep salawadgi 8
log out, again log in, go to account object and check if Match_Billing_Address__c has been created or not.

then try this code


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;
a.ShippingCity=a.BillingCity;
a.ShippingStreet=a.BillingStreet;
a.ShippingState=a.BillingState;
a.ShippingCountry=a.BillingCountry;
}
}
Ashik Ahamed ZahirAshik Ahamed Zahir
Challenge not yet complete in My Trailhead Playground 1

There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Duplicate record found: [Name]
Sagar Herakal 8Sagar Herakal 8
trigger AccountAddressTrigger on Account (before insert,before update) {
   
    for(Account a:Trigger.new){
        if(a.Match_Billing_Address__c==true){
            a.ShippingPostalCode = a.BillingPostalCode;
        }
    }

}
ani ghoani gho
//blank checks !null !empty and ! whitespace....

trigger AccountAddressTrigger on Account (before insert, before update) {
    
    for(Account account : Trigger.New){
        if(String.isNotBlank(account.BillingPostalCode) && account.Match_Billing_Address__c){
            account.BillingPostalCode=account.ShippingPostalCode;
        }
        
    }

}

 
Karan BilakhiyaKaran Bilakhiya
Hi everyone I have tried all above solutions but still getting this error. Can someone plz help:
We updated an account that had 'Match_Billing_Address__c' set to false. We expected the trigger not to fire, but it did. Make sure the trigger fires only if 'Match_Billing_Address__c' is true.
Sonali GajjarSonali Gajjar
Hi everyone!
Please first create checkbox field "Match_Billing_Address__c"and the follow below refernce code in apex trigger
 
trigger AccountAddressTrigger on Account (before insert,before update) {
    
    List<Account> accountList = new List<Account>();
     for(Account a : Trigger.New) {
       
 //here we are matching checkbox true condition and billing value should be not null.
         if(a.Match_Billing_Address__c==true &&  a.BillingPostalCode)
         {
             a.ShippingPostalCode=a.BillingPostalCode;     
             accountList.add(a);
         }
        }  
   }

 
Anup Sharma 31Anup Sharma 31
Please try this code as well,

trigger AccountAddressTrigger on Account (before insert, before update) {
    
    if(Trigger.isInsert){
        for(Account a : Trigger.new){
        If (a.Match_Billing_Address__c == true && a.BillingPostalCode!=Null) {
            a.ShippingPostalCode = a.BillingPostalCode;
        }   
    } 

    }
    
}
 
Sabine ScheuringSabine Scheuring
@Karan Bilakhiya I have the same issue, have you received an answer or found a solution for this already? 
Megha Agrawal 49Megha Agrawal 49
We updated an account that had 'Match_Billing_Address__c' set to false. We expected the trigger not to fire, but it did. Make sure the trigger fires only if 'Match_Billing_Address__c' is true.
getting this error can anyone help me 
this is code below

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;
        }   
    } 

}