You need to sign in to do that
Don't have an account?
Trigger applies to all records instead on relevant ID
Hi. I have a trigger that triggers for more records than I hope for
trigger createOrderforABFSCB on Stem_Cell_Bank__c (after update) { List<ChargentOrders__ChargentOrder__c> co = new List<ChargentOrders__ChargentOrder__c>(); for (Stem_Cell_Bank__c scb : Trigger.new) { if (scb.Stage__c == 'Stem Cells Banked') { /*scb to oscb*/ //initiate the object to put values for furture record ChargentOrders__ChargentOrder__c c = new ChargentOrders__ChargentOrder__c(); //map Order fields to SCB that is being created for this Order c.Stem_Cell_Bank__c = scb.Id; /*scb to oscb*/ c.ChargentOrders__Date__c = date.today(); c.Order_Item__c = 'Yearly Stem Cell Banking Fee'; if(scb.Stem_Cells_Banked_Date__c!=null) c.ChargentOrders__Payment_Start_Date__c = scb.Stem_Cells_Banked_Date__c.addYears(1); else scb.addError('Cannot have empty stem cell bank date before stage is set to stem cell banked'); //add this new object to the list that would be inserted later co.add(c); } //end if } //end for scb //once the loop is done, insert the new record to Order try{ insert co; } catch (system.Dmlexception e) { system.debug(e); } }
This seems to add a new record for all records with stage__c = 'Stem Cells Banked'
I need to add a new ChargentOrder record for existing Stem_Cell_Bank__c record only to the respective ID when Stage__c is updated to 'Stem Cells Banked'
I tried researching more about using oldMap and played around with the logic:
Stem_Cell_Bank__c oscb = Trigger.oldMap.get(scb.ID);
But having a hard time getting it work. Plus if I could add a checksum logic to only allow 2 ChargentOrder records to 1 Stem_Cell_Bank record it will help even more to not encounter these type of errors in the future
Any suggestions would be greatly appreciated
Thank you in advance
Daniel
Hi Daniel,
Try modifying your if() to the following:
For the validation logic you would first need to retrieve any related ChargentOrder__c record that are related and put them in a map, keyed by the scb.id with a list of the orders as the value. Then you can add another if to your body to prevent more from being created if 2 exist.
Hope that gets you started!
if( scb.stage__c != trigger.oldmap.get(scb.ID).stage__c && scb.stage__c == 'Stem Cells Banked')
{
... add your logic
}
As for the checksum, if you the relationship between Stem_Cell_Bank and ChargentOrder is Master-Detail you can do a roll up field and validate on that. However if it is just a lookup relationship, then you would have to include the validation in your trigger. Let me know which it is and I can help you more from there.