APEX Trigger tutorial - update custom object
by
on 02-02-2010 at 09:03 AM (1697 Views)
I stated earlier that I am fairly new to APEX, triggers and classes. I have finally realized that if you want to be successful using Salesforce and their cloud platform that you have to use APEX. I started with the force.com cookbook, which I picked up at Dream Force 2008 and the new APEX cheat sheets that were available in the developers lounge in the Moscone Center.
We needed a simple trigger that would update one custom object in when another one was updated by a user. Now in the past we have accomplished record updates using the Salesforce API and PHP, but in those other developments, we were able to use outbound messaging and workflows.
So here is the first trigger that we actually have in production. This trigger updates another custom object when it is invoked, here is the scenario:
1. Opportunity_Trackers__c - This is the object which users can and possibly will delete. This is where we will place our trigger. This trigger will update another custom object called the Design_Registration__c. The association is the ID field from both objects, cross referencing each other.
2. Design_Registration__c - This is the object that will be updated when the opportunity tracker record is deleted. The system requirements document stated that the design registration record that is associated with the opportunity has to be set to inactive for reporting purposes.
As you can see the trigger is pretty self-explanatory.Code:trigger CleanDRLineItem2 on Opportunity_Tracker_Products__c (before delete) { //This is the ID of the record being deleted List <Id> otIds = new List<Id>(); // Copy each record's id to the list for(Opportunity_Tracker_Products__c ot: Trigger.old) { otIds.add(ot.id); } // Single query - an array of the Design Registrations that need to be updated List <Design_Registration__c> oDRs = [select id, DP_reg_id__c, OwnerID, Inactive__c from Design_Registration__c where Opp_tracker_line_ID__c in :otIds]; //Loop through all the Design Registrations which are returned from the query above //set 4 fields on each DR to specific values and inactivate the record for (Design_Registration__c dr: oDRs) { dr.OwnerId = '00540000000oJjiAAE'; dr.Inactive__c = true; string old_dr_number = dr.DP_reg_id__c; dr.DP_reg_id__c = 'IN-' + old_dr_number; } update oDRs; }
I will be posting more articles on triggers, classes, and test classes in the future.
I hope that you find this beneficial
~Mike
Comments
Leave a Comment









Email Blog Entry
