function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SunaySunay 

Apex Trigger to add line items based on a field

Hi,

 

I need help on building a trigger to add the line items automatically based on a field, where the number is mentioned. As per that number the line items is created automatically. Please find the code for reference which I am working on:

 

trigger OpportunityProductInsert on Opportunity (after insert, after update){

                //USE DESCRIBE METHODS INSTEAD OF SOQL TO GET RECORDTYPEIDS. HELPS IN REDUCING DMLS

 

    Schema.DescribeSObjectResult d = Schema.SObjectType.Opportunity;

    Map<String,Schema.RecordTypeInfo> rtMapByName = d.getRecordTypeInfosByName();

    Id oppRTID = rtMapByName.get('Insert Opp RecordTypeName Here').getRecordTypeId();

//USE MAPS AND LIST TO HOLD DATA

Map<Id,String> currencyisocodemap = new Map<Id, String>();                

    for(Opportunity o :Trigger.new){

                if(o.CurrencyISOCode!=null){

                                currencyisocode.put(o.id, o.CurrencyISOCode);

                }

 

 

    }

//USE RELATIONSHIP QUERIES TO REDUCE SOQLS

 

List<PricebookEntry> pbe = [select Id, CurrencyISOCode from PriceBookEntry where CurrencyISOCode in :currencysiocodemap.keyset() and Pricebook2.isActive = true];

 

Map<String,String> isomap = new Map<String, String>();

 

for(PricebookEntry p  :pbe){

                isomap.put(p.CurrencyISOCode. p.Id);

 

}

 

List<OpportunityLineItem> oppline = new List<OpportunityLineItem>();

 

    for(Opportunity o :Trigger.new){

                //USE LISTS TO HOLD RECORDS BEFORE DOING 'BULK' INSERT

                If(o.N__c>0 && o.RecordTypeId==OppRTId){

                                oppLine.add(new OpportunityLineItem(OpportunityId = o.id, UnitPrice = 0, Quantity = 1, PricebookEntryId = isomap.get(o.CurrencyISOCode));

 

 

 

 

                }

 

 

 

    }

//INSERT OUTSIDE FOR LOOP. BULK INSERT. REDUCE DMLS

if(oppline.size()!=0) insert oppline;

 

}

MattwestMattwest

Did you ever find a solution to this. If so I'd love to know how you accomplished it. Thanks in advance for your response