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
IanSampsonIanSampson 

My First Trigger: Record not updating

Please forgive this really simple example trigger which I'm struggling to get working.

 

I have a Contract record with a custom link to create a new Invoice object. Multiple contracts (children) can reference an Invoice. However when I create a new Invoice, I want the Contract field called "Invoice" to be updated with the InvoiceNumbe, I pass the contract number as a string to the Invoice.

 

 

I've written the trigger in Exclipse, it loads in SF and executes when the Invoice is Updated (I think). But the contract is not updated with the invoice number?

 

trigger trgContractInvoiceNum on Invoices__c (after update) { for (Invoices__c inv : Trigger.new) { Contract ctr = [Select c.Id, c.ContractNumber From Contract c where c.ContractNumber = :inv.SourceContract__c]; ctr.SalesInvoice__c = inv.Id; ctr.Billing_Log__c = inv.Id; / for test purposes } }

 

What silly mistake am I making?

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
DavidPSGDavidPSG

IanSampson,

 

Add this line after populating your ctr fields:

 

Update ctr;

 

 

All Answers

DavidPSGDavidPSG

IanSampson,

 

Add this line after populating your ctr fields:

 

Update ctr;

 

 

This was selected as the best answer
grigri9grigri9

DavidPSG is correct but another thing you want to do is 'bulkify' the trigger. Right now if you update more than 20 Invoices at a time you will hit the SOQL query governor limit. The following is an example of how to bulkify this particular trigger but I obviously havent tested or anything so YMMV. 

 

 

trigger trgContractInvoiceNum on Invoices__c (after update) { set<ID> invoices = new set<id>(); map<Integer,ID> sourcecontractToID = new map<Integer,ID>(); for (Invoices__c inv : Trigger.new) { invoices.add(inv.Id); sourcecontractToID.put(inv.SourceContract__c,inv.Id); } for(List<Contract> ctrs : [Select c.Id, c.ContractNumber From Contract c where c.ContractNumber in :invoices]){ for(Contract ctr : ctrs){ ctr.SalesInvoice__c = sourcecontractToID.get(c.ContractNumber); ctr.Billing_Log__c = sourcecontractToID.get(c.ContractNumber); } update ctrs; } }

 

I believe the apex docs have a bunch of examples of how to write triggers under 'bulk trigger idioms' or someting along those lines.

 

--Greg

 

IanSampsonIanSampson

Thanks a million. Both were invaluable to me and have got me going.

 

Cheers

Ian