To automatically copy the Billing Address into the Shipping Address when the CopyBillingToShipping
checkbox is checked on an Account record, you can create an Apex Trigger on the Account object. This trigger will run when an Account is inserted or updated and will copy the Billing Address fields to the Shipping Address fields if the checkbox (CopyBillingToShipping
) is checked.
trigger CopyBillingToShipping on Account (before insert, before update) {
// Loop through all Account records being inserted or updated
for (Account acc : Trigger.new) {
// Check if the CopyBillingToShipping checkbox is checked
if (acc.CopyBillingToShipping__c == true) {
// Copy Billing Address to Shipping Address
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:
- The trigger is fired on the
before insert
andbefore update
events because we want to copy the Billing Address to the Shipping Address before the Account record is saved to the database.
- The trigger is fired on the
Logic:
- The trigger checks if the
CopyBillingToShipping__c
checkbox is checked (true
). - If the checkbox is checked, it copies the values from the Billing Address fields to the Shipping Address fields. The fields copied include:
- BillingStreet → ShippingStreet
- BillingCity → ShippingCity
- BillingState → ShippingState
- BillingPostalCode → ShippingPostalCode
- BillingCountry → ShippingCountry
- The trigger checks if the
Bulk Processing:
- This trigger is bulkified, meaning it handles multiple Account records in a single transaction.