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
Jia Kang WonJia Kang Won 

how to trigger the product choose at Account and add to opportunity level with apex

User imput a product at Account.
I want a trigger code that able auto add product to opportunity level. Any help.

mycode:
trigger AutoAddProduct 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 = :standardBook.Id];   //set Product using code
        for(Opportunity record: Trigger.new) {
            lines.add(new OpportunityLineItem(PricebookEntryId=entry.Id, OpportunityId=record.Id, UnitPrice=entry.UnitPrice, Quantity=2)); //set Quantity
        }
        insert lines;
    }
}