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
Linda 98Linda 98 

Trigger to set pricebook when creating Opportunity!!

I Think this trigger  would be  easy, but I'm struggling.

This is my requirement i am trying to accomplish with trigger and below is where i got it till.
 How would I write a trigger to set the  active price book on opportunity creation.?
also,other conditions to be satisfied are:
1.If only one pricebook is active,select that.
2.If more than 1 pricebook are active,then select standard pricebook(if its active) if not then select next pricebook based on created date.

My problem is with second point.How can i check if list contains 'Standard pricebook',?  list.contains is not working.
Please suggest.

Below is my code:
 
trigger PBTrigger  on Opportunity (before insert) {

     List<Pricebook2> PBList =  [select id,name from Pricebook2];
     
     if(PBList.Size() <1){
         for(opportunity o:trigger.new){
             if(o.Pricebook2 == null){
                 o.PriceBook2Id =PBList[0].id;
              }
            }
        }
}

 
Head In CloudHead In Cloud
Hi Linda, you can try this:
trigger PBTrigger  on Opportunity (after insert) {

     List<Pricebook2> PBList =  [select id,name from Pricebook2 where isStandard = true];
     list<opportunity> oplist = new list<opportunity>();
     if(PBList.Size() <1){
         for(opportunity o:trigger.new){
             if(o.Pricebook2 == null){
                 o.PriceBook2Id =PBList[0].id;
                 oplist.add(o);
              }
            }
        }
update oplist;
}

 
Linda 98Linda 98
Thank you But my requirement is different. I also may have other pricebooks than standard pb. If i have so,i have to select that if stdpb is inactive. If i am having more than one pb active, i have to select first pb(if std pb is inactive) Your trigger is not even considering other pb as you are querying is standard is true. Hope you got my request!!!
Head In CloudHead In Cloud
I got your requirement now. Please try the below code:
trigger PBTrigger  on Opportunity (after insert) {

     List<Pricebook2> PBList =  [select id,name from Pricebook2 where isStandard = true and isActive = true];
     list<Pricebook2> otherPbks = [select id from pricebook2 where isActive = true order by createdDate limit 1];
     list<opportunity> oplist = new list<opportunity>();
     for(opportunity o:trigger.new){
         if(PBList != null && PBList.Size() >0){
             if(o.Pricebook2 == null){
                 o.PriceBook2Id =PBList[0].id;
                 oplist.add(o);
              }
            }else if(otherpbks != null && otherpbks.size() >0){
                 o.PriceBook2Id =PBList[0].id;
                 oplist.add(o);
            }
        }
update oplist;
}