Wednesday, 12 July 2017

How to add/remove line items on changing multipicklist values with a trigger

Create custom objects with names Proposal, ProposalLineItem, Proposaltemplates.

Create a trigger on Proposal like this,

/*
@author: Balayesu
@date: 7/9/2017
@description: trigger for creating/removing proposal line items
*/
trigger ProposalTriger on Proposal__c (after insert,before update) {
    //create items after inserting a proposal
    if(trigger.isinsert){
        Set<Id> pidset=new Set<Id>();
        for(Proposal__c p:trigger.new){
            pidset.add(p.Id);
        }
        List<Proposal__c> plist=[SELECT Id,Products__c,(SELECT Id,name,Proposal__c FROM Proposal_Products__r) FROM Proposal__c WHERE Id IN:pidset];
        ProposalTrigerHelper.addItems(plist);
    }
    if(trigger.isupdate){
        Map<Id,List<Proposal_Products__c>> plimap=new Map<Id,List<Proposal_Products__c>>();
        for(Proposal__c np:[SELECT Id,Products__c,(SELECT Id,name,Proposal__c FROM Proposal_Products__r) FROM Proposal__c WHERE Id IN:trigger.newMap.keySet()]){
            plimap.put(np.Id,np.Proposal_Products__r);
        }    
        //get the changed proposals
        for(Id pId:Trigger.newMap.keySet()){
            //check if new picklist items not matched with old picklist items
            if(trigger.oldMap.get(pId).Products__c!=trigger.newMap.get(pId).Products__c){
                ProposalTrigerHelper.removeItems(trigger.oldmap,trigger.newmap,plimap);
            }
        }  
    }
}


Create the helper like this,

public class ProposalTrigerHelper {
    //add a line item after inserting a proposal
    public static void addItems(List<Proposal__c> proposals){
        System.debug('Adding Items');
        //create a products list
        List<Proposal_Products__c> productslist=new List<Proposal_Products__c>();        
        for(Proposal__c p:proposals){
            //iterate through all the selected products of multipicklist
            if(p.Products__c!=null){
            for(String pname:(p.Products__c).split(';')){
                if(p.Proposal_Products__r.size()>0){
                    for(Proposal_Products__c pp:p.Proposal_Products__r){
                        //if product doesn't exists
                        if(!pname.equals(pp.name)){ 
                            //add Line items to the list                        
                            productslist.add(new Proposal_Products__c(name=pname,Proposal__c=p.Id,Solution__c=getSolution(pname))); 
                        }
                    }
                }
                else{
                    productslist.add(new Proposal_Products__c(name=pname,Proposal__c=p.Id,Solution__c=getSolution(pname))); 
                }                
            }
            }
                    
        }
        //create line items to the proposal
        try{
            insert productslist;  
        }catch(DMLException de){
            System.debug(de);
        }        
    }
    //remove item if it is unselected before updating it
    public static void removeItems(Map<Id,Proposal__c> oldproposalsMap,Map<Id,Proposal__c> newproposalsMap,Map<Id,List<Proposal_Products__c>> plimap){
        System.debug('Removing Items');
        Map<String,Id> delMap=new Map<String,Id>(); 
        List<Proposal_Products__c> addproductslist=new List<Proposal_Products__c>();  
        List<Proposal_Products__c> delproductslist=new List<Proposal_Products__c>();   
        List<Proposal_Products__c> pitemslist=new List<Proposal_Products__c>();
        System.debug('oldpmap:'+oldproposalsMap+'\n'+'newpMap:'+newproposalsMap);    
        //iterate all old picklist values
        for(Id opId:oldproposalsMap.keySet()){
            if(oldproposalsMap.get(opId).Products__c!=null){
                //delete removed items
                for(String pname:(oldproposalsMap.get(opId).Products__c).split(';')){
                    //if old value is removed from picklist
                    if(!isAvailable(pname,newproposalsMap)){ 
                        System.debug('deleting item: '+pname+'\n No of products: '+plimap.get(opId).size());                    
                        //iterate all the line items
                        for(Proposal_Products__c pp:plimap.get(opId)){
                            System.debug('ppname:'+pp.name);
                            //if product name matches with removed line item
                            if((pp.name).equals(pname)){ 
                                System.debug('Product Added for deletion');
                                delproductslist.add(pp); 
                                //break;
                            }
                        }
                    }
                }
                //check for all the existing ones for their line items
                  for(String pname:(oldproposalsMap.get(opId).Products__c).split(';')){
                      if(!Itemexists(pname,plimap.get(opId))){
                          pitemslist.add(new Proposal_Products__c(name=pname,Proposal__c=opId,Solution__c=getSolution(pname)));
                      }
                  }
            }
        } 
        try{
            delete delproductslist;
        }catch(DMLException de){
            System.debug(de);
        }  
        try{
            insert pitemslist;
        }catch(DMLException e){
            System.debug(e);
        }
        for(Id opId:newproposalsMap.keySet()){
            if(newproposalsMap.get(opId).Products__c!=null){
                for(String pname:(newproposalsMap.get(opId).Products__c).split(';')){
                    //if new value not found in old list
                    if(!isAvailable(pname,oldproposalsMap)){
                        System.debug('products size :'+plimap.get(opId).size());
                        addproductslist.add(new Proposal_Products__c(name=pname,Proposal__c=opId,Solution__c=getSolution(pname)));
                    }
                }
            }
        }
        try{
            insert addproductslist;
        }catch(DMLException e){
            System.debug(e);
        }
    }
    public static String getSolution(String productname){
        String sol='';
        sol=[SELECT Solution__c from Proposal_Product_Solution_Template__c WHERE name=:productname LIMIT 1].Solution__c;
        return sol;
    }
    public static boolean isAvailable(String pname,Map<Id,Proposal__c> proposalsMap){
        boolean flag=false; 
        for(Id npId:proposalsMap.keySet()){
            if(proposalsMap.get(npId).Products__c!=null){
                for(String npname:(proposalsMap.get(npId).Products__c).split(';')){
                    if(npname.equals(pname)){
                        flag=true;                     
                        break;
                    }
                }
            }
        }
        System.debug('isAvailable? '+flag);
        return flag;
    }
    public static boolean Itemexists(String pname,List<Proposal_Products__c> pitemslist){
        boolean flag=false;
        for(Proposal_Products__c item:pitemslist){
            if((item.name).equals(pname)){
                flag=true;
                break;
            }
        }
        return flag;
    }
}



Below is the test class for the above code,

@isTest
public class ProposalTriggerHelper_UT {
    @testsetup
    static void testdata(){
        List<Proposal_Product_Solution_Template__c> templist=new List<Proposal_Product_Solution_Template__c>();
        Proposal_Product_Solution_Template__c temp1=new Proposal_Product_Solution_Template__c();
        temp1.name='Data Modules Organized by Service Type';
        temp1.Solution__c='test sol1';
        templist.add(temp1);
        Proposal_Product_Solution_Template__c temp2=new Proposal_Product_Solution_Template__c();
        temp2.name='Private-Label Member Engagement Tools';
        temp2.Solution__c='test sol1';
        templist.add(temp2);
        insert templist;
        Proposal__c p=new Proposal__c();
        p.Products__c='Data Modules Organized by Service Type;Private-Label Member Engagement Tools';
        insert p;
    }
  @isTest
    static void test1(){
        Proposal__c p=[SELECT Products__c FROM Proposal__c LIMIT 1];
        p.Products__c='Data Modules Organized by Service Type';
        update p;
        System.assertEquals(1,[SELECT name FROM Proposal_Products__c WHERE Proposal__c=:p.Id].size());
    }  
  @isTest
    static void test2(){
        Proposal__c p=[SELECT Products__c FROM Proposal__c LIMIT 1];
        p.Products__c='';
        update p;
        System.assertEquals(0,[SELECT name FROM Proposal_Products__c WHERE Proposal__c=:p.Id].size());
    }
}



No comments:

Post a Comment