+ Start a Discussion
Neeraj Sharma 103Neeraj Sharma 103 

Hi Everyone i have two object one is Standard Object and other One is Custom Object Terriotry

I am beginner in salesforce
So Please Help me out for this scenario
I have two Object one is Standard Object Account and other one is Terriotry object(Territory__c) 
i have create a custom field on territory object Zip Code(Text) 
Zip_Code__c  and Owner Lookup Field(User Lookup) Owner__c
when i create a new zip code and new Owner and then Save the Record

After that i am going on Account Object When i Create a new record and Update a Record and change the BillingPostalCode Field of Account then this Account Owner is Assigned to the New Owner that will be in Territory Object With Some New Zip Code and BillingPostal Code and Zip Code of Territory Object are compared and then Assign the new Owner to that Account to the Account Owner

So Please Help Me I am new in Salesforce i dont know how to write a trigger for this scenario This is My First Trigger So Plese Help Me
Best Answer chosen by Neeraj Sharma 103
Hi Neeraj,
Your rquirement is that, when the Billing Postalcode on Account Object is changed, then Account Owner should be updated with the owner mapped for that zipcode in Territory.

Below is the sample code and it is working in my org.
You may need to tune this code.
This trigger will fire if any of the Field changed on Account. You  need to restric this to fire when BillingPostal code is only changed. You have to use Trigger.new and Trigger.old.

trigger SFDC_TerritoryAssignment on Account (before update) {
      for (Account myAccount : Trigger.new)
           //Get the Billing Postal Code 
            String zipcode = myAccount.BillingPostalCode;
             if (zipcode != null)
                    //Search that Postal Code on Terriroty Object and Get the Owner Name
                 List<Terriotry__c> ListTerritory=[Select Id,Name,OwnerId from Terriotry__c where Zip_Code__c = :zipcode limit 1];
                 system.debug(ListTerritory.size() + 'Owners Found.');               
                                      //Update the Account Owner with this Territory Object Owner Name
                                      system.debug(ListTerritory.get(0).OwnerId + 'Owner Name.');