+ Start a Discussion
KULWANT SINGHKULWANT SINGH 

qoute ineitem trigger

hi, i want to create a trigger on quotes that when i add new product to opportunity then it automatically added to the quote lineitem list......how it can be possible
Agustina GarciaAgustina Garcia
Hi,

Actually the trigger should be related to Opportunity Lines because you want to modify the Quote Lines whenever a new Opportunity line (add a new product to the Opportunity) is created. 

Code could looks like this. NOTE: I don't have Quotes enabled in my org so below code could not compile, but it should looks like this one.
 
trigger OpportunityLineTrigger on OpportunityLineItem (after insert)
{
    List<Id> productIds = new List<Id>();
    Map<Id, List<Id>> oppAndLines = new Map<Id, List<Id>>();
    
    //Look for Opportunities related to these lineas and products.
    for(OpportunityLineItem oppLine : trigger.new)
    {
        if(oppAndLines.keySet().contains(oppLine.OpportunityId))
        {
              productIds = oppAndLines.get(oppLine.OpportunityId);
        }
        else
        {
             productids = new List<Id>();
        }
        productIds.add(oppLine.Product2Id);
        oppAndLines.put(oppLine.OpportunityId, productIds);
    }
    
    //Look for Opportuntiy names related to those Ids that were used in the lines
    List<Id> oppIds = new List<Id>();
    Map<String, List<Id>> oppNameAndIds = new Map<String, List<Id>>(); // 2 opp can have same name
    List<Id> allOppIdsFromLines = oppAndLines.keySet();
    for(Opportunity opp : [Select Id, Name From Opportunity Where Id In :allOppIdsFromLines])
    {
         if(oppNameAndIds.keySet().contains(opp.Name))
         {
             oppIds = oppNameAndIds.get(opp.Name);
         }
         else
         {
             oppIds = new List<Id>();
         }
         oppIds.add(opp.Id);
         oppNameAndIds.put(opp.Name, oppIds);
    }

    //Look for Quotes that are related to Opportunities.
    List<String> oppNames = oppNameAndIds.keySet();
    for(Quote quote : [Select Id, OpportunityName From Quote Where OpportunityName In :oppNames])
    {
           //For each quote look for the opp
           List<Id> quoteOppIds = oppNameAndIds.get(quote.OpportunityName);

           //For each Opp look for products
           for(Id oppId : oppAndLines.keyse())
           {
                 List<Id> productIds = oppAndLines.get(oppId);
                  //Now you have product id and you can create Quote lines with this info

           }
    }
}

Hope this helps