+ Start a Discussion
Benjamin OliverBenjamin Oliver 

Simple Trigger Question - Value Updates Optional Checkbox Field

Hi Community,

I need a trigger to check a Lead's zip code and determine if it matches a set of zip codes that my business services.  If it is a matching zip code, I would like Salesforce to update a checkbox field called 'Local Delivery'.  This way we can identify which Leads are close to our business.  I believe the pseudo code looks like:

trigger UpdateLocalDelivery on Lead (before insert) {
for (Lead lead : trigger.new){
        // if Lead.zip equals one of the following zip codes [22202, 22203, 22204, 22201]
        // then set Lead.Local_Deliver__c = true;
    }

Thank you in advance!

Also, what would the unit test for this trigger look like?
matt.ian.thomasmatt.ian.thomas
I would use a custom setting for this personally and make each zip that you service a row in that custom setting as the Name. I think there may be alternatives but it works pretty well. Try something like this:
trigger UpdateLocalDelivery on Lead (before insert) {
    Map<String, ZipCode__c> zipCodes = ZipCode__c.getAll();

    for (Lead lead : trigger.new) {
        if (lead.Zip != null && zipCodes.get(lead.Zip) != null) {
            lead.Local_Delivery__c = true;
        }
    }
}
Are you sure that before insert is the only context that your trigger should handle? What happens if a lead moves, and the address is updated to reflect that new address, for example?

You could test the trigger in a unit test like this:
@isTest
private class UpdateLocalDeliveryTest {

	private static testmethod void testLocalDelivery1() {
		//In this unit test, we'll test that we do service a particular zip code and that when we insert a lead with that zip code, Local_Delivery__c is true.

		//We have to create a ZipCode__c first.
		ZipCode__c zipCode = new ZipCode__c(Name = '123456');
		insert zipCode;

		//Now we want to insert a new lead with that zip and check Local_Delivery__c
		Lead lead = new Lead(Zip = '123456');
		insert lead;

		system.assert(lead.Local_Delivery__c);
	}
}

I'd also test that inserting a lead with a zip not serviced results in a Local_Delivery__c of false. Hope this helps!

Here is a link to read up on custom settings if you aren't already familiar: https://help.salesforce.com/apex/HTViewHelpDoc?id=cs_about.htm