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
mayrich1mayrich1 

Inserting New Custom Objects Records

Hi,

 

I have created a custom object that has a couple text and picklist fields on it.  The custom object is a child of the Opportunity object.  Whenever an opportunity is created I would like to automatically create a couple new custom objects with the same data in them every time.  Any sample code to get me started would be greatly appreciated.


Thank you

Best Answer chosen by Admin (Salesforce Developers) 
jrotensteinjrotenstein

Your code should look something like the following (warning: this code has not been tested):

 


trigger addChildren on Opportunity (after insert) {

List<sObject> childrenToAdd = new List<sObject>;

for (Opportunity o : Trigger.new) {
Child__c child1 = new Child__c(Field1 = 'hello', Field2 = 'there', OpportunityId = o.id);
Child__c child2 = new Child__c(Field1 = 'good', Field2 = 'day', OpportunityId = o.id);
childrenToAdd.add(child1);
childrenToAdd.add(child2);
}

insert childrenToAdd;
}
Message Edited by jrotenstein on 02-16-2009 02:29 PM

All Answers

jeffdonthemicjeffdonthemic

You'll want to create a trigger that fires whenever a new Opportunity is created. The Apex Reference guide has more than enough code to get you going. You'll also want to ensure that it supports bulk processing.

 

Jeff Douglas
Informa Plc
http://blog.jeffdouglas.com

mayrich1mayrich1

Thank you for the response Jeff.  I looked through the manual and I did not see an example that showed how to automatically add records for a child custom object to the opportunity record every time an opportunity record has been created.  I am familiar with creating new records, but I am not sure how to relate the custom object records to the opportunity record.  Does it do this automatically since the trigger kicks off from the opportunity?

 

Thank you,
Ben

jrotensteinjrotenstein

Your code should look something like the following (warning: this code has not been tested):

 


trigger addChildren on Opportunity (after insert) {

List<sObject> childrenToAdd = new List<sObject>;

for (Opportunity o : Trigger.new) {
Child__c child1 = new Child__c(Field1 = 'hello', Field2 = 'there', OpportunityId = o.id);
Child__c child2 = new Child__c(Field1 = 'good', Field2 = 'day', OpportunityId = o.id);
childrenToAdd.add(child1);
childrenToAdd.add(child2);
}

insert childrenToAdd;
}
Message Edited by jrotenstein on 02-16-2009 02:29 PM
This was selected as the best answer
mayrich1mayrich1
Thanks John! It is working now.