[SalesForce] how to insert records in an object only when there are no records present in it before

How to insert records in an object only when there are no records present in it before… the following trigger inserts records in payment_schedule object(child to opportunity) when a checkbox is true.

The problem is,it keeps on inserting whenever i update something!! :(.Only once record should be inserted

trigger generatePS on Opportunity (after insert,after update) {
List<Id> projectIds = new List<Id>();
id Oid;
for(opportunity opp :Trigger.new) {
    if(opp.Generate_Payment_Schedule__c == true )
    {
        projectIds.add(opp.project_name__c);
        oid = opp.id;
    }
}
system.debug('Project ID'+ projectIds);  
List<Payment_Schedule__c> ps = new List<Payment_Schedule__c>();
List<Payment_Schedule_Template__c> pst = [select name,Project__c,Due_Date__c,Amount_Percentage_Made__c from Payment_Schedule_Template__c where Project__c in :projectIds ];
system.debug('PST'+ pst);

    for(Payment_Schedule_Template__c psinsert:pst)
    {

        Payment_Schedule__c payshcedule = new Payment_Schedule__c();
        payshcedule.name = psinsert.name;
        payshcedule.Amount_Percentage_Made__c = psinsert.Amount_Percentage_Made__c;
        payshcedule.Due_Date__c = psinsert.Due_Date__c;
        payshcedule.Opportunity__c = Oid;
        ps.add(payshcedule);

    }


    system.debug('Payment Schedule to insert'+PS);

     insert ps;
     }

What am I doing wrong ?

Best Answer

Ok, first of all, do you want your code to run both on insert or also on update?

If you would let the code run only on insert, when checking your box Generate_Payment_Schedule__c after the record was inserted, the code wouldn't run.

If your code should run only on insert, remove the "after update" from your trigger. (first line)

If your code should run on both insert and update, you will need to check if the Generate_Payment_Schedule__c checkbox was changed from false to true.

@Phil Hawthorn posted the following samplecode on how to compare the "old" to the "new" values (Just update when a specific field changes):

for( Account accountId : Trigger.newMap.keySet() )
{
  if( Trigger.oldMap.get( accountId ).Antecipado__c != Trigger.newMap.get( accountId ).Antecipado__c )
  {
     // do something here because your field has changed
  }
}

You should use such code to check for which opportunities it needs to generate the child records.

Related Topic