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
Manish Anand 10Manish Anand 10 

Trailhead challenge: Apex with Triggers

Create an Apex trigger for Account that matches Shipping Address Postal Code with Billing Address Postal Code based on a custom field.
I am writing following code:-

trigger AccountAddressTrigger on Account (before insert,before update)
{
    List <Account> act= [Select id,name from Account where BillingPostalCode != NULL and Match_Billing_Address__c='True' ];
        For(Account a:act)
       {
           a.ShippingPostalCode=BillingPostalCode;
            }
}

It gives error-Varibale Doesn't exist:BillingPostalCode. 

What I am missing here?
Note- In the challenge, it's given, ShippingPostalCode and BillingPostalCode are the API name, 
Best Answer chosen by Manish Anand 10
Mahesh DMahesh D
Hi Manish,

Please find the below code:
 
trigger AccountAddressTrigger on Account (before insert, before update) {
	
	for(Account acc : Trigger.new) {
		if(acc.Custom_Field__c) {
			acc.ShippingPostalCode = acc.BillingPostalCode;	
		}
	}
}

Here you need to replace the if condition with your Custom Field API name along with the proper condition, if it is checkbox type then just changing the name will be enough. If it is other Data Type then have to change the condition using == operator.

Please do let me know if it helps you.

Regards,
Mahesh

All Answers

Subhash GarhwalSubhash Garhwal
Use a.ShippingPostalCode = a.BillingPostalCode;
Mahesh DMahesh D
Hi Manish,

Please find the below code:
 
trigger AccountAddressTrigger on Account (before insert, before update) {
	
	for(Account acc : Trigger.new) {
		if(acc.Custom_Field__c) {
			acc.ShippingPostalCode = acc.BillingPostalCode;	
		}
	}
}

Here you need to replace the if condition with your Custom Field API name along with the proper condition, if it is checkbox type then just changing the name will be enough. If it is other Data Type then have to change the condition using == operator.

Please do let me know if it helps you.

Regards,
Mahesh
This was selected as the best answer
Muhammad AlaaMuhammad Alaa
trigger AccountAddressTrigger on Account (before insert, before update) {
    //Match_Billing_Address__c is TRUE then ShippingPostalCode Matches BillingPostalCode
    for (Account a : Trigger.New){
        if (a.Match_Billing_Address__c)
             a.ShippingPostalCode = a.BillingPostalCode;
    }
}

 
kuldeep paliwalkuldeep paliwal
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;

    }
}
}