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
SFDC DEV1SFDC DEV1 

Add opportunity products in Opportunity using Apex triggers. I need this urgent task.

Hello everyone, I am new with triggers.
Can someone help me to write a trigger on opportunity and opportiunites must have account (s) for adding multiples opportunity products from custom and standard pricebook.
 
AbhishekAbhishek (Salesforce Developers) 
Use below code snippet  to update all account associated with Opportunites in Trigger


trigger updateAccountIfOppCustomer on Opportunity (after insert, after update) {
    
    List<Account> acctToUpdate = new List<Account>();
    List<Opportunity> opps = new List<Opportunity>(); 
    
    Set<Id> associatedAccId = new Set<Id>() ;
    for (Opportunity opp : Trigger.new) {
        associatedAccId.add(opp.AccountId) ;
    }
    
    opps = [SELECT Id, AccountId, StageName, Account.Type FROM Opportunity WHERE AccountId in =: associatedAccId];
    
    for (Opportunity opp : opps) {
            if (opp.StageName == 'Closed Won - One Time' || o.StageName == 'Closed Won - Recurring' || o.StageName == 'Customer Reseller') {   
                Opp.Account.Type  = 'Customer';
                acctToUpdate.add(Opp.Account) ; 
            }
           else {
                opp.Account.Type = 'Prospect';
                acctToUpdate.add(Opp.Account) ;
            }
    }
    update acctToUpdate;
}


You might have to make some changes based on your requirements.

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

 
SFDC DEV1SFDC DEV1
Thank You Abhishek...
AbhishekAbhishek (Salesforce Developers) 
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.