You need to sign in to do that
Don't have an account?

Add record in custom object after insert in another custom object
I need to add a record to a custom object after I insert a record into another custom object. I have the trigger working for a straight forward insert, but I don't want to insert the record if a record already exists with that customer number. Here is the code for my existing trigger. The matching field in both custom objects is JDE_Cust__c;
trigger GetAcctIdTrigger on Sales_History__c (after insert) {
list <sales_history_comp__c> newshc = new list<sales_history_comp__c>();
for (Sales_History__c sh : Trigger.new){
system.debug('GeT SH = ' + sh);
sales_history_comp__c ishc = new sales_History_Comp__c();
ishc.Account__c = sh.Customer__c;
ishc.JDE_Cust__c = sh.JDE_Cust__c;
ishc.Customer_Name__c = sh.Cust_Name__c;
ishc.Sales_History__c = sh.id;
ishc.Comp_Year_1__c = sh.sales_Year__c;
ishc.Comp_Year_2__c = '0000';
system.debug('ISHC RECORDS = ' +ishc);
newshc.add(ishc);
}
insert newshc;
}
Better Yet:
All Answers
1. Create a SET to hold some JDE_Cust__c values (string, integer, decimal, whatever type it is .) [ex. IncomingCusts]
2. Loop through trigger.new, to retrieive all the JDE_Cust__c values coming into the trigger, and place them into this SET.
3. Query sales_history__c WHERE JDE_Cust__c IN :IncomingCusts
4. Create another SET to hold the items that aready exist [ex. ExistingCust].
5. Loop through the query results and get the existing Custs JDE_Cust__c value and place it into this new set.
6. Now add your existing code into the trigger, but just before the "new sales_history__c statement, add an if statement
list <sales_history_comp__c> newshc = new list<sales_history_comp__c>();
for (Sales_History__c sh : Trigger.new){
system.debug('GeT SH = ' + sh);
if (! ExistingCust.Contains(sh.JDE_Cust__c)) //Note the NOT expression
{
<your code>
}
}
insert newshc;
}
Better Yet:
Thanks for the quick response.
I have installed
As a different way of thinking about it, you should also use declarative features. So, just to ask, have you declared the sales_History_Comp__c.JDE_Cust__c field to be a unique field?
If you did that, then your original trigger would have come along, tried to create a new Sales_History_Comp__c record and failed because of the uniqueness criteria. The entire trigger would have rolled back. If you threw exception handling code into your trigger (which is always a good idea anyway), you'd be able to catch the exception so it didn't propogate further back to the user with an ugly error message.
Even if you use the code provided (which is ostensibly better since it does the checking up front), you should still probably set the uniqueness constraint.
Best, Steve.