function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
utz1utz1 

Child record exist then do not create child record

Hello,
I want some changes in my code suppose there is already invoice record for opportunity then it should not create invoice when we update opportunity
trigger CreateNewQuote on Opportunity(after insert , after update) {

        
        for (Opportunity o1 : Trigger.new){
        if(o1.StageName  == 'Closed Won' ){
     
        Invoice__c newInvoice = new Invoice__c();
        System.debug('New Inovice Is Created');
         newInvoice.Account__c = o1.AccountId;
         newInvoice.Opportunity__c = o1.Id;
         newInvoice.Quote__c =  o1.SyncedQuoteId;
       //newInvoice.Pricebook2Id = o1.Pricebook2Id;

        insert newInvoice;
        System.debug('Invoices Created with data:='+newInvoice); 

    }
    }      
}
}
Best Answer chosen by utz1
Shamsi 110Shamsi 110
 
 set<Id> setOfOpportunities = new set<Id>();
  for (Opportunity opp : Trigger.new){
       setOfOpportunities.add(opp.Id);
  }
 
 integer InvoiceRelatedOpportunityCount = [Select count() from Invoice__c where opportunityid in : setOfOpportunities];
 
 for (Opportunity o1 : Trigger.new){
        if(o1.StageName  == 'Closed Won' && InvoiceRelatedOpportunityCount >0  ){
     
        Invoice__c newInvoice = new Invoice__c();
        System.debug('New Inovice Is Created');
         newInvoice.Account__c = o1.AccountId;
         newInvoice.Opportunity__c = o1.Id;
         newInvoice.Quote__c =  o1.SyncedQuoteId;
       //newInvoice.Pricebook2Id = o1.Pricebook2Id;

        insert newInvoice;
        System.debug('Invoices Created with data:='+newInvoice); 

    }
    }      
 

All Answers

Shamsi 110Shamsi 110
 
 set<Id> setOfOpportunities = new set<Id>();
  for (Opportunity opp : Trigger.new){
       setOfOpportunities.add(opp.Id);
  }
 
 integer InvoiceRelatedOpportunityCount = [Select count() from Invoice__c where opportunityid in : setOfOpportunities];
 
 for (Opportunity o1 : Trigger.new){
        if(o1.StageName  == 'Closed Won' && InvoiceRelatedOpportunityCount >0  ){
     
        Invoice__c newInvoice = new Invoice__c();
        System.debug('New Inovice Is Created');
         newInvoice.Account__c = o1.AccountId;
         newInvoice.Opportunity__c = o1.Id;
         newInvoice.Quote__c =  o1.SyncedQuoteId;
       //newInvoice.Pricebook2Id = o1.Pricebook2Id;

        insert newInvoice;
        System.debug('Invoices Created with data:='+newInvoice); 

    }
    }      
 
This was selected as the best answer
utz1utz1
Thank you Shamsi. Its working
Shamsi 110Shamsi 110
Good to hear It is working :)