+ Start a Discussion
Sitarama MurthySitarama Murthy 

Auto assign Pricebook to Opportunity based on in to which pricebook the user profile have access

Hi All,

I am Stuck with selecting the pricebook for Opportunity based on user profile.
Scenario is: I have Custom Page to Add product to Opportunity(Add Line Item) page is accessed using list Button from product related list in Opportunity. What i need is Pricebook to Opportunity should be assigned automatically based on the user profile who is creating the Line item.

each profile having access to only one pricebook.
selection of Pricebook to Opportunity should happen in Apex code.

Please help on how can i query the to which pricebook the current profile who is access the page have access?

Sibasish PanigrahiSibasish Panigrahi
Hi Ram,

Assuming you have a User Lookup (User__c) in Pricebook, let's query the Pricebook in Apex:
Pricebook2 pr = [Select Id, Name From Pricebook2 Where User__c =: UserInfo.getUserId()];

This will get you the PriceBook of the current User. As it's an one-to-one relation with user we don't have to worry about the 'n' number of Pricebook for this User.

Now once we get the Pricebook, use the Pricebook id in Opportunity:
Opportunity opp = new Opportunity();
opp.Pricebook2 = pr.Id;

Hope this helps to solve the issue.