Here is the trigger:Trigger MoveToProduction on Opportunity (before insert, before update){ List<ID> ProjIds = New List<ID>(); for(Opportunity o : Trigger.new){ if(o.Move_to_Production__c == true && o.RecordTypeId == '012a0000001FqTn'){ ProjIds.add(o.Project__c); } List<Project__c> ProjList = [SELECT id, Move_to_ProductionP__c, Date_Pushed_to_Production__c FROM Project__c WHERE id in :ProjIds]; for(integer i = 0 ; i < ProjList.size(); i++){ If(ProjList[i].Date_Pushed_to_Production__c == null) ProjList[i].Move_to_ProductionP__c = true; ProjList[i]. Date_Pushed_to_Production__c = system.today(); update ProjList;
4 respostas
Richie has the right answer. I'd like to share a couple techniques that will help to avoid duplicating code between insert and update blocks, and use some other best practices.<pre>// first, move to after insert, after update, since we are not modifying the Opportunity objecttrigger MoveToProduction on Opportunity (after insert, after update){ // query record type so we don't have to hard-code RecordType IDs RecordType oppRT = [ SELECT Id FROM RecordType WHERE sObjectType = 'Opportunity' AND DeveloperName = 'Desired_Record_Type' ]; // use a Set because multiple Opportunities could look up to the same Project Set<Id> projIds = new Set<Id>(); for ( Opportunity opp : Trigger.new ) { // get the old version of the record - null if insert Opportunity oldOpp = Trigger.isUpdate ? Trigger.oldMap.get( opp.Id ) : null; if ( opp.Move_to_Production__c // it's boolean - no need to compare to true && (oldOpp == null || !oldOpp.Move_to_Production__c) && opp.RecordTypeId == oppRt.Id ) { projIds.add( opp.Project__c ); } } if ( !prjIds.isEmpty() ) { // exclude Projects with non-null Date_Pushed_to_Production__c // since we're not going to update those List<Project__c> projList = [ SELECT Id, Move_to_ProductionP__c, Date_Pushed_to_Production__c FROM Project__c WHERE Id in :projIds AND Date_Pushed_to_Production__c = null ]; for ( Project__c proj : projList ) { proj.Move_to_ProductionP__c = true; proj.Date_Pushed_to_Production__c = System.today(); } update projList; }}</pre>