+ Start a Discussion

Creating OpportunityLIneItems based on different related objects

Ihave following code
public class generateBundle {

  public static void generate(Set<Id> Ids) {
  set<id> BundleProductsIds = new set<id>();
  set<id> Products = new set<id>();
  set<id> Pricebookentry = new set<id>();
  map<id, PriceBookentry> myMap = new map<id, PriceBookentry>();
  map<id,Bundle__c> BundleMap = new map <id,Bundle__c>();
  map<id,OpportunityLineItem>  OpportunityMap = new map<id,OpportunityLineitem>();
  List<OpportunityLineItem> Opportunityli = new List<OpportunityLineItem>();
List<opportunityLineItem> lineItem = [select id, product2id,OpportunityId,TotalPrice from Opportunitylineitem where id in:ids];
      for(OpportunityLineitem oli : lineItem) {
        Products.add(oli.product2id );
        OpportunityMap.put(oli.id, oli);

List <Bundle__c> Bundle =[select id,IncludeIntheBundle__c,PriceBook__c,Bundle__c,Weight__c, BundleProductID__c  from Bundle__c where IncludeIntheBundle__c IN :Products];
        for(Bundle__c Bp : Bundle) {
        BundleMap.put(bp.id, bp);
List<PriceBookentry> pbeids = [Select id,product2id, pricebook2id from priceBookentry where product2id in: BundleProductsIds and isActive= TRUE  ];
        for(PriceBookentry pbe : pbeids) {
        myMap.put(pbe.id,pbe );

                                OpportunityLI.add(New OpportunityLIneitem
                                   totalPrice= (BundleMap.get(bp.id).Weight__c)/100*OpportunityMap.get(oli.id).totalPrice
    insert    OpportunityLI; 



Idea behind is this
if a user selects special product form the list, thathas 2 or more other products attached to it via Junction it shoudl add those product in as well.
error i get with it is
Error: Compile Error: Variable does not exist: oli.id at line 43 column 69

however if i nest for loop with SOQL querries it works, but creates multiple items instead of one, and it is not bulk safe anyway, any help great appreciated
OLI is declared on line 15 but only for the scope of the for loop that ends on line 19.  

I reckon you want to wrap lines 40-46 inside an iterator, but that iterator needs to be able to access the bundle products associated with the original order line item, and I can't see that you have that information anywhere.