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
kevinjia1984kevinjia1984 

Question about creating new records when a record created

Hi all,

 

I am a newbie in this area. I want to realize that When a new Publication_Mention__c record is inserted into the database with the Referral__c checkbox ticked  a new Opportunity  with a Product line item associated against the Opportunity will be created.

 

Below is the trigger:

 

 

trigger NewPublicationMentionTrigger on Publication_Mention__c(before insert, before update) {

 NewPublicationMention.createNewOpportunity(Trigger.New);

}

 

 

Here is the class:

 

 

public with sharing class NewPublicationMention {
 public static void createNewOpportunity(List<Publication_Mention__c> PublicationMentions)
 {
 for(Publication_Mention__c PM: PublicationMentions)
 {
 //when the Referral__c checkbox ticked
 if(PM.Referral__c==True)
 {
 //a new Opportunity object will be created
 Opportunity newOpportunity = new Opportunity();
 
 //a new Product object will be created
 Product2 newProduct = new Product2();
 
 //fields of the new Opportunity object
 newOpportunity.Name = newOpportunity.Contact_Name__r.FirstName + newOpportunity.Contact_Name__r.LastName + '-' + newOpportunity.Product__r.Name;
 newOpportunity.StageName = 'New';
 newOpportunity.CloseDate = Date.today();
 newOpportunity.Type = 'Free';
 newOpportunity.Order_Source__c = 'Helpline';
 newOpportunity.Order_Date__c = Date.today();
 newOpportunity.Amount = 0;
 
 //fields of the new Product object
 newProduct.Quantity_in_Stock__c = 1;
 newProduct.Price__c = 0.00;
 newProduct.First_Publication_Date__c = Date.today();
 }
 }
 }
}

 

 

I have tested it with creating a publication mention object. But no Opportunity and product record created. Can some one help me out with the wrong part. Thanks a lot

*werewolf**werewolf*

You are missing 3 key things:

 

1.  You have to call create on the Opportunity so that it gets submitted to the database.

2.  Once that create has returned, the Opportunity object will have its Id field filled in.  You'll need that to fill the OpportunityId of the...

3.  OpportunityLineItem.  To add a line item to Opportunity, that's what you want to add, not Product, and its OpportunityId field needs to be filled in order to be associated with the Opportunity (and you'll probably need to fill in its PricebookEntryId also, which is what relates it to the product).  Don't forget to call create on your OpportunityLineItem too!