• Vaibhav Parashar 2
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 4
    Replies
Trigger to delete a record in product when a field in opportunity is changed?
Trigger to delete a record in product when a field in opportunity is changed?
Hi

I am a newbie and I wrote the trigger code below to test a field to see whetherit has been updated then if so call new code...  when i runs i get the error below..  If anyone can help me to resolveit, would be greatly appreciated
THe code is meant to check Pricebook2id to see if it has changed, then if it has changed load all the products from the pricebook into the opportunity

Update failed. First exception on row 0 with id 00661000002hNvAAAU; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateProduct: execution of BeforeUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry is in a different pricebook than the one assigned to the opportunity): [PricebookEntryId] Class.PricebookPicklist.updateRecords:"
 
trigger UpdateProduct on Opportunity (before update) {    for(Opportunity o: Trigger.new)
    {
        if(system.trigger.OldMap.get(o.Id).Pricebook2Id != system.trigger.NewMap.get(o.Id).Pricebook2Id)
        {
            //Populate records
            PricebookPicklist obj = new PricebookPicklist();
            obj.updateRecords(system.trigger.NewMap.get(o.Id).Id, system.trigger.NewMap.get(o.Id).Pricebook2Id);
   
            o.NextStep = 'Changed';
           
        }
        else
        {
            o.NextStep = 'Unchanged';
        }
    }
}

   public PageReference updateRecords(String oppid, String id)
    {
        Opportunity opp = [Select pricebook2Id from Opportunity where Id = :oppid]; //Find opportunity page using the parameter
        List<PricebookEntry> pbeList = [Select Product2.ProductCode, UnitPrice, Product2ID From PricebookEntry where pricebook2Id = :id];
        List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
        for(PricebookEntry pbe: pbeList)
         {
                OpportunityLineItem oli = new OpportunityLineItem();
                oli.OpportunityId = opp.id;
                oli.PricebookEntryId = pbe.id;
                oli.Quantity = 1;
                oli.UnitPrice = pbe.UnitPrice;
                oliList.add(oli);
        }
        insert oliList;
        return null;  
    }

 

HI,

Is there a way i cna delete existing related records under opporttunity such as product, when some oportunity fied changes? how would  go about it? any sample code would be gretly apreciated

  • May 03, 2011
  • Like
  • 0