Here’s an Apex Trigger that automatically copies the Billing Address fields into the Shipping Address fields when an Account is inserted and the CopyBillingToShipping checkbox is checked.
trigger CopyBillingToShipping on Account (before insert) {
for (Account acc : Trigger.new) {
// Check if CopyBillingToShipping__c is true
if (acc.CopyBillingToShipping__c == true) {
acc.ShippingStreet = acc.BillingStreet;
acc.ShippingCity = acc.BillingCity;
acc.ShippingState = acc.BillingState;
acc.ShippingPostalCode = acc.BillingPostalCode;
acc.ShippingCountry = acc.BillingCountry;
}
}
}
Explanation of the Code
Trigger Event:
- Runs on the
before insert
event to modify the Shipping Address fields before the record is saved to the database.
- Runs on the
Logic:
- Checks if the custom checkbox field CopyBillingToShipping__c (assumed to be a custom field) is
true
. - Copies all relevant Billing Address fields into their respective Shipping Address fields.
- Checks if the custom checkbox field CopyBillingToShipping__c (assumed to be a custom field) is
Bulk Processing:
- Iterates over all records in
Trigger.new
to ensure it works for bulk inserts.
@isTest
private class CopyBillingToShippingTest {
@isTest
static void testCopyBillingToShipping() {
// Test Case 1: Account with CopyBillingToShipping__c = true
Account billingToShippingAccount = new Account(
Name = 'Billing to Shipping Account',
BillingStreet = '123 Billing St',
BillingCity = 'Billing City',
BillingState = 'Billing State',
BillingPostalCode = '12345',
BillingCountry = 'Billing Country',
CopyBillingToShipping__c = true
);
insert billingToShippingAccount;
// Query the inserted Account
Account insertedAccount = [SELECT ShippingStreet, ShippingCity, ShippingState, ShippingPostalCode, ShippingCountry
FROM Account
WHERE Id = :billingToShippingAccount.Id];
System.assertEquals('123 Billing St', insertedAccount.ShippingStreet, 'ShippingStreet should match BillingStreet');
System.assertEquals('Billing City', insertedAccount.ShippingCity, 'ShippingCity should match BillingCity');
System.assertEquals('Billing State', insertedAccount.ShippingState, 'ShippingState should match BillingState');
System.assertEquals('12345', insertedAccount.ShippingPostalCode, 'ShippingPostalCode should match BillingPostalCode');
System.assertEquals('Billing Country', insertedAccount.ShippingCountry, 'ShippingCountry should match BillingCountry');
// Test Case 2: Account with CopyBillingToShipping__c = false
Account noCopyAccount = new Account(
Name = 'No Copy Account',
BillingStreet = '456 Billing St',
CopyBillingToShipping__c = false
);
insert noCopyAccount;
// Query the non-copied Account
Account noCopyInsertedAccount = [SELECT ShippingStreet FROM Account WHERE Id = :noCopyAccount.Id];
System.assert(noCopyInsertedAccount.ShippingStreet == null, 'ShippingStreet should remain null when CopyBillingToShipping__c is false');
}
}