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

Trigger that creates child record on creation of parent record only if checkbox is true

I was wondering if someone could help a newb to SFDC come up with the code for an apex trigger.


Here's the scenario:


I have a custom object called payments (Payments__c) - a child object  of opportunities - and I would like a payment record to be created after a new opportunity record is created, but only if a checkbox is checked (Create_New_Payment__c).


There are a few fields on the new payment record that need to be pre-populated:

  1. The opportunity field (obviously)
  2. Payment amount (Amount__c) should equal the amount of the opportunity (the payment amount field is not a formula field and can't be, but maybe this can be accomplished with workflow - if Create_New_Payment__c is true, payment amount equals opportunity amount??)
  3. Paid__c checkbox equals true

So is this possible to do?


Thanks for any help.


Here's the basic trigger:



trigger CreatePayments on Opportunity (after insert) { List<Payments__c> createpayments = new List <Payments__c> {}; for (opportunity o : { if (o.create_new_payment__c == true) { createpayments.add(new Payments__c ( Opportunity__c = o.Id, amount__c = o.amount, paid__c = true)); } } try { insert createpayments; } catch (Exception Ex) { system.debug(Ex); } }



I believe you could also update the Amount field on the Payments object after creation via workflow using a cross object formula 

Message Edited by BritishBoyinDC on 09-30-2009 05:55 PM

This was great. and worked like a charm.


how do we create related records and existing accounts (opportunities in example)





Not sure I follow - are you asking how to create related records for accounts related to the Opportunity? Or something else?


Do you also have a test class created for it.


having trouble creating the test class.




This trigger works fine. Can someone write a decent test class for it so I can migrate it to production? This is not a skillset I've yet developed. Many thanks.