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
Nick KeehanNick Keehan 

Apex Trigger - If Check before firing

Hey Guys.

Can anyone help with adding a condition for below to fire?

e.g.  if(opp.Product_Name_String__c != '') 

This should only fire when there is something added into Product Name String.

Its mentioned below however it still fires when the string field is empty?

Any ideas?
 
trigger oppLineItem on Opportunity (after insert) {
    Map<id,Set<id>> oppIdProNameMap = new Map<id,Set<Id>>();
    Set<Id> priceBookIdSet = new Set<id>();

    {
    for(Opportunity opp : trigger.new)
        {
        priceBookIdSet = new Set<Id>();
        system.debug('---opp.Product_Name_String__c--'+opp.Product_Name_String__c);
        if(opp.Product_Name_String__c != '')
        {
            priceBookIdSet=getPriceBookId(opp.Product_Name_String__c,opp.Pricebook2Id); 
            system.debug('---priceBookIdSet---'+priceBookIdSet);
            oppIdProNameMap.put(opp.Id, priceBookIdSet);
        }            
    }
    List<OpportunityLineItem> newLineItemsList = new List<OpportunityLineItem>();
    for(id oppId : oppIdProNameMap.keySet()){
        for(id pBId : oppIdProNameMap.get(oppId)){
            OpportunityLineItem lineItem = new OpportunityLineItem (OpportunityID= oppId,PriceBookEntryID=pBId, quantity=1,TotalPrice = 100,Contract_Term__c ='12');
            newLineItemsList.add(lineItem);
        }    
    }
    insert newLineItemsList;
    } 

    public Set<id> getPriceBookId(string pName,id bookId){
        List<String> proName = new List<String>();
        proName = pName.split(',');        
        Map<id,product2> proIdMap = new Map<id,product2>([Select id from product2 where name IN: proName]);
        system.debug('----proIdMap.keySet()--'+proIdMap.keySet());
        Map<id,PricebookEntry> priceBookMap = new Map<id,PricebookEntry>([SELECT Id,IsActive,Product2Id,UnitPrice FROM PricebookEntry WHERE Product2Id IN: proIdMap.keySet() and Pricebook2Id =: bookId]);
        return priceBookMap.keySet();
    }
}

Thanks
Best Answer chosen by Nick Keehan
Prateek Singh SengarPrateek Singh Sengar
hi Nick,
Can you try, isBlank function of String class the syntax goes like this
 
if(!String.isBlank(opp.Product_Name_String__c))

Hope this helps.

All Answers

Prateek Singh SengarPrateek Singh Sengar
hi Nick,
Can you try, isBlank function of String class the syntax goes like this
 
if(!String.isBlank(opp.Product_Name_String__c))

Hope this helps.
This was selected as the best answer
Nick KeehanNick Keehan
Perfect, thanks!