write a trigger when invoice line item is created in invoice object, Invoice__c field…
- User
write a trigger when invoice line item is created in invoice object, Invoice__c field has to update in InvoiceLineItem object
- Assistant
Trigger:
codetrigger UpdateInvoiceField on Invoice_Line_Item__c (after insert) { //get the list of invoice ids to update Set<Id> invoiceIds = new Set<Id>(); for(Invoice_Line_Item__c ili : trigger.new){ invoiceIds.add(ili.Invoice__c); } //update the invoice fields List<Invoice__c> invoicesToUpdate = new List<Invoice__c>(); for(Invoice__c invoice : [SELECT Id, Invoice_Line_Item_Count__c FROM Invoice__c WHERE Id IN :invoiceIds]){ invoice.Invoice_Line_Item_Count__c = [SELECT count() FROM Invoice_Line_Item__c WHERE Invoice__c = :invoice.Id]; invoicesToUpdate.add(invoice); } //update the invoices in bulk update invoicesToUpdate; }This trigger fires after an record is inserted. It first gets a list of all the records that are related to the new records being inserted. It then updates the field on those records, based on the number of related records. Finally, it updates the records in bulk.
- User
write a trigger to update opportunityId field in quote object by referencing the id field in opportunity object
- Assistant
Trigger:
codetrigger UpdateOpportunityIdOnQuote on Quote (before insert, before update) { for(Quote quote : trigger.new){ if(quote.OpportunityId == null) { //lookup the Opportunity object based on the Opportunity Name field Opportunity opp = [SELECT Id, Name FROM Opportunity WHERE Name = :quote.Opportunity_Name__c LIMIT 1]; if(opp != null){ quote.OpportunityId = opp.Id; } else { //Opportunity not found based on name quote.addError('Opportunity not found for name ' + quote.Opportunity_Name__c); } } } }