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
Alastair1988Alastair1988 

APEX Code Trigger to Add product when opportunity is created

I need help writing a small tigger to automatically add a product to an opportunity when created.

 

This will happen on every opportunity and will be the same product everytime. Can anyone point me in the right direction or provide a coded example?

 

Thansk, 

sfdcfoxsfdcfox
trigger X on Opportunity (before insert, after insert) {
    Pricebook2 standardBook = [SELECT Id FROM Pricebook2 WHERE IsStandard = true];
    if(Trigger.isBefore) {
        for(Opportunity record: Trigger.new) {
            record.Pricebook2Id = standardBook.Id;
        }
    }
    if(Trigger.isAfter) {
        OpportunityLineItem[] lines = new OpportunityLineItem[0];
        PricebookEntry entry = [SELECT Id, UnitPrice FROM PricebookEntry WHERE Pricebook2Id = :standardBook.Id AND Product2.ProductCode = 'DEFAULT'];
        for(Opportunity record: Trigger.new) {
            lines.add(new OpportunityLineItem(PricebookEntryId=entry.Id, OpportunityId=record.Id, UnitPrice=entry.UnitPrice, Quantity=1));
        }
        insert lines;
    }
}

This is a rough estimate of the code you'll want to use. We need to set the price book before adding the product, so we do this in "before insert", then we add the product in the event "after insert". You may need to adjust the fields to suit your needs as well.