+ Start a Discussion
Scott CarlsonScott Carlson 

Beginning Trigger - Set Opp Pricebook from Account Values

I'm trying to learn about triggers in SF - and am working on my first task: a trigger that will set an Opportunity price book based on two Account field values.

GPO__c is a text field
GPO_Tier__c is a number

I'm trying to set the Opportunity Price Book based on these field values. Example - if the Account GPO is "GPO A" and the GPO Tier is 1, it should match a price book with the name of "GPO A Tier 1".

Here's some code I've put together so far:

trigger SetOppPriceBook4 on Opportunity (before insert) {
	for(Opportunity o : trigger.new){
        List<Account> acct = [SELECT GPO__c, GPO_Tier__c, Id FROM Account WHERE ID = :o.AccountId]; 
        List<Pricebook2> pb = [SELECT id from Pricebook2 WHERE Name = :acct[0].GPO__c + ' Tier ' + :acct[0].GPO_Tier__c];
        	o.PriceBook2Id = pb[0].id;
        else {o.Pricebook2Id = NULL;

I think I'm running into some problems with concatenating within the select statement. What do I need to change
Best Answer chosen by Scott Carlson
Daniel B ProbertDaniel B Probert
i'd create a formula field on my opportunity that isn't visible on the page layout then use this trigger.

trigger InsertPriceBookTrigger on Opportunity (before insert) {
    for(Opportunity Opp : Trigger.New ){
        Id priceBookId= [select id,name from Pricebook2 where Name=:opp.PriceBookAccount__c].Id;
        Opp.PriceBook2Id =priceBookId;

formula field PriceBookAccount = Account.GPO__c + ' ' + Account.GPO_Tier__c

if this helps mark as resolved :)