+ 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;
        }
    }
Rajeevan SRajeevan S
Hey Rachidy Imane,

Yeah I got it and able to find out why. This is because Discount Percentage and Discount Percentage Status is Mandatory for Oppurtunity.

Please find this code, it will solve your problem..

trigger AddRelatedRecords on Account(after insert, after update) {
    List<Opportunity> oppList = new List<Opportunity>();
   
    Map<Id,Account> acctsWithOpps = new Map<Id,Account>(
        [SELECT Id,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
    System.debug(acctsWithOpps);
    for(Account a : Trigger.New) {
        System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities.size());
        
        if (acctsWithOpps.get(a.Id).Opportunities.size() == 0) {
            oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       Discount_Percent__c=100,    
                                       Discount_Percent_Status__c='Approved',

                                       AccountId=a.Id));
                                     //Two fields are Mandatory for Oppurtunity
        }           
    }
    System.debug(oppList);
    if (oppList.size() > 0) {
        insert oppList;
    }
}
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?
Young Hwan KimYoung Hwan Kim
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]