
Hello Community,
I have a trigger for a custom object . I need to update a field of that custom object based on Product Entry UnitPrice.
Unfortunatelly, I can't find a way how to get a UnitPrice of a product of selected Price Book
Can anybody point me to a right derection?
here is my trigger:
trigger CPBXdeployment102 on Hosted_PBX_Deployment__c (before insert, before update) {
Set<Id> oppIds = new Set<Id>();
for(Hosted_PBX_Deployment__c newHPBX : Trigger.new)
{if(newHPBX.Opportunity__c !=null){oppIds.add(newHPBX.Opportunity__c);}}
List<Opportunity> hpbxOpportunity = [SELECT Id,OwnerId, Pricebook2Id FROM Opportunity WHERE id in :oppIds];
Map<Id, Opportunity>OppToHPBXMap = new Map<Id,Opportunity>();
for (Opportunity o :hpbxOpportunity) {OppToHPBXMap.put(o.Id,o);}
for(Hosted_PBX_Deployment__c newHPBX : Trigger.new){Opportunity OName = OppToHPBXMap.get(newHPBX.Opportunity__c); if(OName!=null){newHPBX.Opportunity_Name__c = OName.Id;newHPBX.Opportunity_Owner__c = OName.OwnerId;newHPBX.Price_Book__c = OName.Pricebook2Id;}}
}
try below code trigger CPBXdeployment102 on Hosted_PBX_Deployment__c(before insert, before update) {
Set < Id > oppIds = new Set < Id > ();
list < PricebookEntry > PBEs = [Select Id, Name, Pricebook2Id, Product2Id, UnitPrice from PricebookEntry];
Map < Id, PricebookEntry > PBEMap = new Map < Id, PricebookEntry > ();
for (PricebookEntry pb: PBEs) {
PBEMap.put(pb.Pricebook2Id, pb);
}
for (Hosted_PBX_Deployment__c newHPBX: Trigger.new) {
if (newHPBX.Opportunity__c != null) {
oppIds.add(newHPBX.Opportunity__c);
}
}
List < Opportunity > hpbxOpportunity = [SELECT Id, OwnerId, Pricebook2Id FROM Opportunity WHERE id in: oppIds];
Map < Id, Opportunity > OppToHPBXMap = new Map < Id, Opportunity > ();
for (Opportunity o: hpbxOpportunity) {
OppToHPBXMap.put(o.Id, o);
}
for (Hosted_PBX_Deployment__c newHPBX: Trigger.new) {
Opportunity OName = OppToHPBXMap.get(newHPBX.Opportunity__c);
if (OName != null) {
newHPBX.Opportunity_Name__c = OName.Id;
newHPBX.Opportunity_Owner__c = OName.OwnerId;
newHPBX.Price_Book__c = OName.Pricebook2Id;
PriceBookEntry PBE = PBEMap.get(OName.PriceBook2Id);
if(PBE != null){
system.debug(PBE);
system.debug(PBE.UnitPrice);
}
}
}
}