• Subhodeep Dey 1
  • NEWBIE
  • 10 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 6
    Replies
HI All,

I have created a batch class below in which CONTACT is parent object and alu_Application__c is a child object the retion field name is Applicant__c, I need to update the value of contact Prefered Name with alu_Application__c Prefered Name. I tried to excutethe same but it's not working.

global class ContactUpdate implements Database.Batchable<sObject>
{    
    global string query;
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        system.debug('Check1');
        query = 'SELECT Id,Preferred_Name__c, Applicant__c FROM alu_Application__c';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<alu_Application__c> scope)
    {    
        system.debug('scope'+scope);
        try    
        {
            List<Contact> appCon = new List<Contact>();
            for (alu_Application__c ap : scope)
            {    
                system.debug('ap'+ap);
                Contact con = new Contact();
                con.Id = ap.Applicant__c;
                con.Preferred_Name__c = ap.Preferred_Name__c;
                appCon.add(con);
            }
            system.debug('appCon'+appCon);
            if(appCon.size() > 0)
            {
                update appCon;
                system.debug('appCon'+appCon);
            }
        }
        catch(Exception e)
        {
            system.debug('Error ');
        }
    }  
    global void finish(Database.BatchableContext BC)
    {
        system.debug('Check');
    }
}

Please helip me ASAP, It's really an urgent task for me!

Thanks,
 
Class code:-

public class ReportClass {
    public Campaign CampignDetails{get;set;}
    public List<CampaignMember> campaignMemberRecords {get; set;}
    public List<Opportunity> opportunityLists {get; set;}
    public set<String> campaignMemberStatus {get; set;}
    public List<wrapClass> wrpperValues {get; set;}
    public Map<Id, Boolean> OpportunityPresentOrNot {get; set;}
    public Map<id, Set<String>> opportunityStageCampaignMemberIdMap {get; set;} //Camp id with opportunity Stage
    public Map<Id, Map<string, integer>> opportunityTotalNumWithStage {get; set;}
    public Map<Id, Map<string, Decimal>> opportunityTotalAmountWithStage {get; set;}
    public Map<Id, Decimal> campaignMemberWithopportunityTotalAmount {get; set;}
    public ReportClass(){
        campaignMemberRecords = new List<CampaignMember>();
        opportunityLists = new List<Opportunity>();
        campaignMemberStatus = new set<String>();
        opportunityStageCampaignMemberIdMap = new Map<id, Set<String>>(); //Got
        wrpperValues = new List<wrapClass>();
        OpportunityPresentOrNot = new Map<Id, Boolean>();
        Set<id> campaignMembersId = new Set<id>();
        opportunityTotalNumWithStage = new Map<Id, Map<string, integer>>();
        opportunityTotalAmountWithStage = new Map<Id, Map<string, Decimal>>();
        campaignMemberWithopportunityTotalAmount = new Map<Id, Decimal>();
        
        /*-----------------------*/
        String cmpId;
        if(test.isRunningTest()){
           Campaign cp = new Campaign();
             cp.Name = 'Test Account' ;
            cp.IsActive = TRUE;
            insert cp;
            cmpId = cp.id;
        }
        else if(!test.isRunningTest()){
           cmpId = ApexPages.currentPage().getParameters().get('id');
        }
        
        /*----------------------*/
        CampignDetails = [SELECT Id,name,Number_of_Sent__c,Number_of_Responded__c,NumberOfContacts,
                          NumberOfOpportunities,NumberOfWonOpportunities,AmountAllOpportunities,AmountWonOpportunities
                       //   from Campaign WHERE ID=:ApexPages.currentPage().getParameters().get('id')];
                            from Campaign WHERE ID=:cmpId];
        /*----------------------*/
        
        List<Opportunity> allOpportunity = new List<Opportunity>();
        List<Opportunity> temporaryOpportunityList = new List<Opportunity>();
        Map<id, List<opportunity>> champAndopportunityMap = new Map<id, List<opportunity>>();
        //To fetch CampaignMember
        for(CampaignMember cmpMem:[SELECT name,CampaignId,ContactId,Campaign_Active__c,Campaign_Name__c,CompanyOrAccount,Email,FirstName,
                                   HasResponded,LastName,Member_City__c,Member_State__c,Member_Street__c,Member_Zip__c,
                                   Phone,Status FROM CampaignMember WHERE CampaignId =:ApexPages.currentPage().getParameters().get('id') ]){
            campaignMemberRecords.add(cmpMem);
            campaignMembersId.add(cmpMem.ContactId);
            campaignMemberStatus.add(cmpMem.Status); // To get campaignMember Status
        }
        
        
        //To fetch Opportunity
        for(Opportunity op : [SELECT AccountId,Account.Name,Campaign.Name,npsp__Primary_Contact__r.Name,
                              Amount,CampaignId,CloseDate,Name,npsp__Primary_Contact__c,RecordTypeId,RecordType.Name, 
                              StageName FROM Opportunity WHERE npsp__Primary_Contact__c IN: campaignMembersId AND
                              CampaignId = :ApexPages.currentPage().getParameters().get('id')]){
        allOpportunity.add(op);
        }
       
       // To fetch campaignMembers Id with List<opporutnity> and Opportunity Stage
        for(id ids : campaignMembersId){
             temporaryOpportunityList = new List<opportunity>();
            for(opportunity op : allOpportunity){
                if(op.npsp__Primary_Contact__c == ids){
                    temporaryOpportunityList.add(op);
                }
            }
            if(temporaryOpportunityList.size() > 0){
                OpportunityPresentOrNot.put(ids, True);
            }
            else{
                OpportunityPresentOrNot.put(ids, False);
            }
            Set<String> OpportunityStageSet = new Set<String>();
            for(opportunity op : temporaryOpportunityList){
                OpportunityStageSet.add(op.StageName);
            }
            opportunityStageCampaignMemberIdMap.put(ids,OpportunityStageSet);
            champAndopportunityMap.put(ids, temporaryOpportunityList);
        }
        
        //To fetch Total amount and Total no of records per stage
        for(id ids : campaignMembersId){
            List<Opportunity> TempOppList = new List<Opportunity>();
            Map<string, integer> TempOppStageWithTotalNo = new Map<string, integer>();
            Map<string, Decimal> TempOppStageWithTotalAmount = new Map<string, Decimal >();
            for(string oppStage : opportunityStageCampaignMemberIdMap.get(ids)){
                TempOppList = new List<Opportunity>();
                for(Opportunity opp :champAndopportunityMap.get(ids)){
                    Decimal totalAmount = 0;
                    if(opp.StageName == oppStage){
                        TempOppList.add(opp);
                    }
                    if(TempOppList.size() > 0 ){
                    for(Opportunity oppTemp : TempOppList){
                        totalAmount += oppTemp.Amount;
                    }
                    }
                    else{
                        totalAmount = 0;
                    }
                    TempOppStageWithTotalAmount.put(oppStage, totalAmount);
                    TempOppStageWithTotalNo.put(oppStage, TempOppList.size());
                }
                
            }
            opportunityTotalNumWithStage.put(ids, TempOppStageWithTotalNo);
            opportunityTotalAmountWithStage.put(ids, TempOppStageWithTotalAmount);
        }
        system.debug(opportunityTotalAmountWithStage);
        
        for(id ids : campaignMembersId){
            Decimal totalOpportunityAmount = 0;
            for(Opportunity opp :champAndopportunityMap.get(ids)){
                totalOpportunityAmount += opp.Amount;
            }
            campaignMemberWithopportunityTotalAmount.put(ids, totalOpportunityAmount);
        }
        
        //Put value in WRAPPER CLASS
        for(campaignMember campaignMemberRec : campaignMemberRecords){
            wrpperValues.add(new wrapClass(campaignMemberRec, champAndopportunityMap.get(campaignMemberRec.ContactId), champAndopportunityMap.get(campaignMemberRec.ContactId).size(), campaignMemberWithopportunityTotalAmount.get(campaignMemberRec.ContactId), campaignMemberStatus, opportunityStageCampaignMemberIdMap.get(campaignMemberRec.ContactId),OpportunityPresentOrNot.get(campaignMemberRec.ContactId), opportunityTotalNumWithStage.get(campaignMemberRec.ContactId), opportunityTotalAmountWithStage.get(campaignMemberRec.ContactId)));
        }
        
    }

    //Wrapper Class
    public class wrapClass{
        public CampaignMember campaignMemberRecordForWrap {get; set;} //got
        public List<Opportunity> opportunityListsForWrap {get; set;}  //got
        public Integer totalNoOfOpportunityWrap {get; set;}
        public Decimal totalAmountOfOpportunityWrap {get; set;}
        public Set<String> campaignMemberStatusForWrap {get; set;} //got
        public Set<String> OpportunityStagesForWrap {get; set;} //got
        public boolean OpportunityPresentOrNotForWrap {get; set;}
        public Map<string, integer> opportunityTotalNumWithStageForWrap {get; set;}
        public Map<string, Decimal> amountWithOpportunityStagesForWrap {get; set;}
        //public Map<String, Integer> amountWithOpportunityStagesForWrap {get; set;}   , Map<String, Integer> amountWithOpportunityStages
        public wrapClass(CampaignMember campaignMemberRecord, List<Opportunity> opportunityLists, Integer totalNoOfopportunity, Decimal totalAmountOfOpportunity, Set<String> campaignMemberStatus, Set<String> OpportunityStages, Boolean OpportunityPresentOrNot, Map<string, integer> opportunityTotalNumWithStage, Map<string, Decimal> opportunityTotalAmountWithStage){
            campaignMemberRecordForWrap = campaignMemberRecord;
            opportunityListsForWrap = opportunityLists;
            totalNoOfOpportunityWrap = totalNoOfopportunity;
            totalAmountOfOpportunityWrap = totalAmountOfOpportunity;
            campaignMemberStatusForWrap = campaignMemberStatus;
            OpportunityStagesForWrap = OpportunityStages;
            OpportunityPresentOrNotForWrap = OpportunityPresentOrNot;
            opportunityTotalNumWithStageForWrap = opportunityTotalNumWithStage;
            amountWithOpportunityStagesForWrap = opportunityTotalAmountWithStage;
        }
    }
}

Current test class code with pass and 60% code coverage

@isTest(SeeAllData = true)
public class ReportClass_Test {

    static testMethod void TestCampaignMember (){
        Test.startTest();
        Account testAcc = new Account (Name = 'Test Account');{
        insert testAcc;
        }
        Id cmpRecordTypeId = Schema.SObjectType.Campaign.getRecordTypeInfosByName().get('Marketing Campaign').getRecordTypeId();
        
        //Creates Contact to be linked to Campaign Member
        Contact testContact = new Contact(FirstName = 'TestContactF', LastName = 'TestContactL', Email = 'none@gmail.com',accountid=testAcc.Id);
        insert testContact;
        
        Campaign cp= [SELECT Id,name,Number_of_Sent__c,Number_of_Responded__c,NumberOfContacts,
                          NumberOfOpportunities,NumberOfWonOpportunities,AmountAllOpportunities,AmountWonOpportunities
                          from Campaign limit 1];
    
        //Creates a new campaign memeber, associaites it with 1 provider sales campaign, and inserts
        CampaignMember newMember = new CampaignMember(ContactId = testContact.id, status='Sent', campaignid = cp.id);
        insert newMember;
     
         Opportunity testOpp = new Opportunity (Name = 'Test Name',                       
                                     AccountId = testAcc.Id,
                                     StageName = 'Asked',
                                     Amount = 50000.00,
                                     CloseDate = System.today(),
                                     campaignid = cp.id,
                                     npsp__Primary_Contact__c =testContact.id
                                     );
        insert testOpp;
     
        Opportunity testOpp1 = new Opportunity (Name = 'Test Name1',                       
                                     AccountId = testAcc.Id,
                                     StageName = 'Received',
                                     Amount = 10000.00,
                                     CloseDate = System.today() + 1,
                                     campaignid = cp.id,
                                     npsp__Primary_Contact__c =testContact.id
                                     );
        insert testOpp1; 
    
        List<Opportunity> opList = new List<Opportunity>();
        opList.add(testOpp);
        opList.add(testOpp1); 
        
        Set<String> memStatus =new Set<String> ();
        memStatus.add(newMember.Status);
        
        Set<String> opStage =new Set<String> ();
        opStage.add(testOpp.StageName); 
        opStage.add(testOpp1.StageName); 
        
        Map<string, integer> opportunityTotalNumWithStage = new  Map<string, integer>();
        opportunityTotalNumWithStage.put(testOpp.StageName,1);
        Map<string, Decimal> opportunityTotalAmountWithStage = new Map<string, Decimal>();
        opportunityTotalAmountWithStage.put(testOpp.StageName, 50000.00);
    
         
        ReportClass rc= new ReportClass();
        rc.campaignMemberRecords.add(newMember);
        ReportClass.wrapClass rcWrp = new  ReportClass.wrapClass(newMember,opList,1,50000.00,memStatus,opStage,true,opportunityTotalNumWithStage,opportunityTotalAmountWithStage);
              
        Test.stopTest();

    }
}
Trigger:-

trigger CloneInternshipOpportunityTrigger on alu_Internship_Cycle__c  after insert, before update, after update, before delete, after delete, after undelete){
    if(Trigger.isInsert && Trigger.isAfter){
        CloneInternshipOpportunity.createInternshipOpportunity(Trigger.new);
    }
}

Helper class:-
public class CloneInternshipOpportunity {
    
    @InvocableMethod
    public static void createInternshipOpportunity(List<alu_Internship_Cycle__c> internCycle) {
        try{
            
            Map<Id,alu_Internship_Cycle__c> mapIdbyNewInternCyc = new  Map<Id,alu_Internship_Cycle__c>();
            
            //Fetch Existing Internship cycle      
            for(alu_Internship_Cycle__c newInternCyc : internCycle){   
               mapIdbyNewInternCyc.put(newInternCyc.Id, newInternCyc);
            }
            
            Map<Id,alu_Internship_Cycle__c> mapIdbyOldInternCyc = new Map<Id,alu_Internship_Cycle__c> ([
                SELECT Id, Name, Start_Date__c 
                FROM alu_Internship_Cycle__c 
                WHERE Id NOT IN: mapIdbyNewInternCyc.keySet() 
                AND Start_Date__c =: mapIdbyNewInternCyc.values().Start_Date__c.addYears(-1) ]);
            
            System.debug('mapIdbyOldInternCyc '+mapIdbyOldInternCyc);
            
            List<Opportunity> oppListByOldCyc = [
                SELECT id, Name, RecordTypeId, AccountId, Account.Name, Internship_Cycle__c, Internship_Cycle__r.Name, CloseDate,  StageName 
                FROM Opportunity 
                WHERE Internship_Cycle__c IN: mapIdbyOldInternCyc.KeySet()
            ];
            
             System.debug('oppListByOldCyc '+oppListByOldCyc);
            
            //Set<Opportunity> oppsToClone = new Set<Opportunity>();
            List<Opportunity> oppsToClone = new List<Opportunity>();
            
            for(Id tmp : mapIdbyNewInternCyc.keySet()){                 
                for(Opportunity opp : oppListByOldCyc){
                    Opportunity opps = new Opportunity();
                    opps.Name = 'Clone Opportunity';
                    opps.RecordTypeId = opp.RecordTypeId;
                    opps.CloseDate = opp.CloseDate;
                    opps.StageName = opp.StageName;
                    opps.AccountId = opp.AccountId;
                    opps.Internship_Cycle__c = tmp;
                    oppsToClone.add(opps);
                    
                }
            }
            insert oppsToClone;
            
            System.debug('Opportunity>>>'+oppsToClone);
            
            }catch (Exception e){
            system.debug('Error '+e.getMessage() +' '+e.getLineNumber());
        }
        
     } 
}

I have a task assigned to clone child record with new parent identity by referring the parent StartDate fields value with the record contains exactly one-year difference value. 

Means:-

If Internship Cycle 'Cycle 1' have date 1/1/2016  and have 10 child records 'opportunities', If a user will create a new  Internship Cycle record 'Cycle 2' have date 1/1/2017. Then it'll clone all the opportunities from 'Cycle 1' to 'Cycle 2' with new parent identity.
This task needs to be in upsert logic on the opportunity. i.e., if the 'Cycle 1's one of the child records 'opportunity 1' will update, then the cloned opportunity from 'opportunity 1' needs to be updated.
 
This is a high priority task for me, plz help me!  :)
 

 
 
HI All,

I have created a batch class below in which CONTACT is parent object and alu_Application__c is a child object the retion field name is Applicant__c, I need to update the value of contact Prefered Name with alu_Application__c Prefered Name. I tried to excutethe same but it's not working.

global class ContactUpdate implements Database.Batchable<sObject>
{    
    global string query;
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        system.debug('Check1');
        query = 'SELECT Id,Preferred_Name__c, Applicant__c FROM alu_Application__c';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<alu_Application__c> scope)
    {    
        system.debug('scope'+scope);
        try    
        {
            List<Contact> appCon = new List<Contact>();
            for (alu_Application__c ap : scope)
            {    
                system.debug('ap'+ap);
                Contact con = new Contact();
                con.Id = ap.Applicant__c;
                con.Preferred_Name__c = ap.Preferred_Name__c;
                appCon.add(con);
            }
            system.debug('appCon'+appCon);
            if(appCon.size() > 0)
            {
                update appCon;
                system.debug('appCon'+appCon);
            }
        }
        catch(Exception e)
        {
            system.debug('Error ');
        }
    }  
    global void finish(Database.BatchableContext BC)
    {
        system.debug('Check');
    }
}

Please helip me ASAP, It's really an urgent task for me!

Thanks,
 

Hi All,

 

I am facing bulkification issue on creating multiple child records from insert multiple parent record using data loader. It's showing  "10:53:29:088 FATAL_ERROR System.LimitException: Too many DML rows: 10001".

 

Please help me for fixing the issue.

 

trigger OppTrigger on Opportunity (after insert, after update, before delete) {
    
    // Record Insert Code
    if(trigger.isInsert || trigger.isundelete){
        if(checkRecursive.runOnce()){
            Set<Id> oppId = new Set<Id>();
            Map<Id,Opportunity> oppmap = new Map<Id,Opportunity>();
            for(Opportunity opp: Trigger.new){
                oppId.add(opp.Id);
            }
            List<Projected_Opportunity__c> proOppList = new List<Projected_Opportunity__c>();
            for(Opportunity opps: [SELECT ID,Name,StageName,Probability,
                                   CloseDate,Month_No__c,Implementation_Date__c,
                                   Contract_Term__c,Amount,Projected_Revenue_1__c,
                                  Q1RF_target__c,Total_Project_Revenue__c FROM Opportunity WHERE ID IN:oppId]){
                  
                 for(Integer i=0; i< Integer.valueOf(opps.Contract_Term__c); i++){
                      Projected_Opportunity__c  po = new Projected_Opportunity__c();
                        po.Opportunity__c = opps.Id; 
                        po.Opportunity_Name__c = opps.Name; 
                        po.Stage__c = opps.StageName;
                        po.Probability__c = opps.Probability;
                        po.Closed_Date__c = opps.CloseDate;
                        po.Month_No__c = opps.Month_No__c;
                        po.Projected_Implementation_Date__c = opps.Implementation_Date__c.addMonths(i);
                        po.Contract_Term__c=opps.Contract_Term__c;
                        po.Amount__c = opps.Amount;
                        po.Monthly_Projected_Revenue__c = opps.Projected_Revenue_1__c;
                        po.Target_Revenue__c = opps.Q1RF_target__c;
                        po.Total_Project_Revenue__c = opps.Total_Project_Revenue__c;
                        proOppList.add(po);
                }                      
                
            }
            if(!proOppList.isEmpty()){
                insert proOppList;
            }
            

        /*    List<Projected_Opportunity__c> polistInsertRecords = new List<Projected_Opportunity__c>();
          for(Opportunity opps: Trigger.new){
                   for(Integer i=0; i< Integer.valueOf(opps.Contract_Term__c); i++){
                      Projected_Opportunity__c  po = new Projected_Opportunity__c();
                        po.Opportunity__c = opps.Id; 
                        po.Opportunity_Name__c = opps.Name; 
                        po.Stage__c = opps.StageName;
                        po.Probability__c = opps.Probability;
                        po.Closed_Date__c = opps.CloseDate;
                        po.Month_No__c = opps.Month_No__c;
                        po.Projected_Implementation_Date__c = opps.Implementation_Date__c.addMonths(i);
                        po.Contract_Term__c=opps.Contract_Term__c;
                        po.Amount__c = opps.Amount;
                        po.Monthly_Projected_Revenue__c = opps.Projected_Revenue_1__c;
                        po.Target_Revenue__c = opps.Q1RF_target__c;
                        po.Total_Project_Revenue__c = opps.Total_Project_Revenue__c;
                        polistInsertRecords.add(po);
                } 
                
            }
            system.debug('polistInsertRecords ' + polistInsertRecords); 
            if(!polistInsertRecords.isEmpty()){
                insert polistInsertRecords;
            }*/
            /*try{
                if(polistInsertRecords.size() >0){
                       insert polistInsertRecords; 
                         system.debug('Record Inserted...');  
                    }
                 }catch(DmlException  e){
                    system.debug(e.getMessage());
                    system.debug(e.getLineNumber());
              }    */
        } 
    }
    //Code for update records
    if(trigger.isUpdate){
        if(checkRecursive.runOnce()){
            Set<Id> oppids = new Set<Id>();
            List<Projected_Opportunity__c> polistInsertRecords = new List<Projected_Opportunity__c>();
          
            for(Opportunity op : trigger.new){
            
                 oppids.add(op.id);
                
            }
            
           
            List<Projected_Opportunity__c> proOppForDel = new List<Projected_Opportunity__c>([Select Id,Opportunity_Name__c,Amount__c,
                                                                                                       Closed_Date__c,Stage__c,Probability__c,
                                                                                                     Projected_Implementation_Date__c,Contract_Term__c,
                                                                                                     Monthly_Projected_Revenue__c,Target_Revenue__c 
                                                                                              From Projected_Opportunity__c 
                                                                                              Where Opportunity__c IN:oppids]);
                                                    
            Delete proOppForDel;
            
            for(Opportunity opps : Trigger.new){ 
                for(Integer i=0; i< opps.Contract_Term__c; i++){
                      Projected_Opportunity__c  po = new Projected_Opportunity__c();
                        po.Opportunity__c = opps.Id; 
                        po.Opportunity_Name__c = opps.Name; 
                        po.Stage__c = opps.StageName;
                        po.Probability__c = opps.Probability;
                        po.Closed_Date__c = opps.CloseDate;
                        po.Month_No__c = opps.Month_No__c;
                        po.Projected_Implementation_Date__c = opps.Implementation_Date__c.addMonths(i);
                        po.Contract_Term__c=opps.Contract_Term__c;
                        po.Amount__c = opps.Amount;
                        po.Monthly_Projected_Revenue__c = opps.Projected_Revenue_1__c;
                        po.Target_Revenue__c = opps.Q1RF_target__c;
                        po.Total_Project_Revenue__c = opps.Total_Project_Revenue__c;
                        polistInsertRecords.add(po);
              
                  } 
                }system.debug('polistInsertRecords ' + polistInsertRecords); 
             try{
                if(polistInsertRecords.size() >0){
                       insert polistInsertRecords; 
                         system.debug('Record Inserted...');  
                    }
                }catch(DmlException  e){
                    system.debug(e.getMessage());
                    system.debug(e.getLineNumber());
             }    
        } 
     }
}