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
MattyDHLMattyDHL 

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY & SELF_REFERENCE_FROM_TRIGGER

Hi,

 

I have spent 9 hours on this trigger and I really am unsure why I am getting these errors? The thing is this is simular to many tiggers I have wrote in the past so its hard for me to understand.


The trigger is trying to change the currency of a Lead to USD whenever the record type is NA Leads.

 

I would appreciate any help at all. Many Thanks for your time.

 

Trigger:

trigger NALeadsWeb2LeadCurrencyChange on Lead (before update) { Map<String,String> LeadMap = new Map<String,String>(); for(Lead l:trigger.new){ if (l.RecordTypeId == [ select Id from RecordType where Name = 'NA Lead' and SobjectType = 'Lead' limit 1].id){ LeadMap.put(l.id, 'USD'); } } List<Lead> recordsforupdates = new list<Lead>(); for(Lead nl : [Select Id, CurrencyIsoCode from Lead where Id IN : LeadMap.keySet()]){ if (LeadMap.containsKey(nl.Id)){ nl.CurrencyIsoCode = 'USD'; recordsforupdates.add(nl); } } update recordsforupdates; }

 

Test Case:

@isTest private class NALeadsWeb2LeadCurrencyChanger { static testMethod void myUnitTest() { // TO DO: implement unit test Lead lead = new Lead(firstname= 'TestTestTest', lastname = 'Testing', company = 'Salesforce.com', email = 't.test@salesforce.com', recordtypeid =[select Id from RecordType where Name = 'ADMIN Master Web to Lead' and SobjectType = 'Lead' limit 1].Id); insert lead; lead.RecordTypeId=[select Id from RecordType where Name = 'NA Lead' and SobjectType = 'Lead' limit 1].id; update lead; } }

 

Error:

*** Beginning Test 1: NALeadsWeb2LeadCurrencyChanger.static testMethod void myUnitTest() 20100218162913.636:Class.NALeadsWeb2LeadCurrencyChanger.myUnitTest: line 10, column 22: SOQL query with 1 row finished in 5 ms 20100218162913.636:Class.NALeadsWeb2LeadCurrencyChanger.myUnitTest: line 11, column 4: Insert: SOBJECT:Lead 20100218162913.636:Class.NALeadsWeb2LeadCurrencyChanger.myUnitTest: line 11, column 4: DML Operation executed in 146 ms 20100218162913.636:Class.NALeadsWeb2LeadCurrencyChanger.myUnitTest: line 13, column 22: SOQL query with 1 row finished in 4 ms 20100218162913.636:Class.NALeadsWeb2LeadCurrencyChanger.myUnitTest: line 15, column 4: Update: SOBJECT:Lead *** Beginning NALeadsWeb2LeadCurrencyChange on Lead trigger event BeforeUpdate for 00QS0000003OZhJ 20100218162913.823:Trigger.NALeadsWeb2LeadCurrencyChange: line 3, column 2: SelectLoop:LIST:SOBJECT:Lead 20100218162913.823:Trigger.NALeadsWeb2LeadCurrencyChange: line 4, column 25: SOQL query with 1 row finished in 16 ms 20100218162913.823:Trigger.NALeadsWeb2LeadCurrencyChange: line 3, column 2: Number of iterations: 1 20100218162913.823:Trigger.NALeadsWeb2LeadCurrencyChange: line 13, column 2: SelectLoop:LIST:SOBJECT:Lead 20100218162913.823:Trigger.NALeadsWeb2LeadCurrencyChange: line 13, column 16: SOQL query with 1 row finished in 21 ms 20100218162913.823:Trigger.NALeadsWeb2LeadCurrencyChange: line 13, column 2: Number of iterations: 1 20100218162913.823:Trigger.NALeadsWeb2LeadCurrencyChange: line 19, column 2: Update: LIST:SOBJECT:Lead 20100218162913.823:Trigger.NALeadsWeb2LeadCurrencyChange: line 19, column 2: DML Operation executed in 2 ms System.DmlException: Update failed. First exception on row 0 with id 00QS0000003OZhJMAW; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 00QS0000003OZhJ) is currently in trigger NALeadsWeb2LeadCurrencyChange, therefore it cannot recursively update itself: [] Trigger.NALeadsWeb2LeadCurrencyChange: line 19, column 2 Cumulative resource usage: Resource usage for namespace: (default) Number of SOQL queries: 4 out of 100 Number of query rows: 4 out of 500 Number of SOSL queries: 0 out of 20 Number of DML statements: 3 out of 100 Number of DML rows: 3 out of 500 Number of script statements: 10 out of 200000 Maximum heap size: 0 out of 1000000 Number of callouts: 0 out of 10 Number of Email Invocations: 0 out of 10 Number of fields describes: 0 out of 10 Number of record type describes: 0 out of 10 Number of child relationships describes: 0 out of 10 Number of picklist describes: 0 out of 10 Number of future calls: 0 out of 10 Number of find similar calls: 0 out of 10 Number of System.runAs() invocations: 0 out of 20 Total email recipients queued to be sent : 0 Static variables and sizes: NALeadsWeb2LeadCurrencyChange:LeadMap:29 NALeadsWeb2LeadCurrencyChange:recordsforupdates:58 Stack frame variables and sizes: Frame0 l:0 nl:0 *** Ending NALeadsWeb2LeadCurrencyChange on Lead trigger event BeforeUpdate for 00QS0000003OZhJ 20100218162913.636:Class.NALeadsWeb2LeadCurrencyChanger.myUnitTest: line 15, column 4: DML Operation executed in 74 ms System.DmlException: Update failed. First exception on row 0 with id 00QS0000003OZhJMAW; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, NALeadsWeb2LeadCurrencyChange: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 00QS0000003OZhJMAW; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 00QS0000003OZhJ) is currently in trigger NALeadsWeb2LeadCurrencyChange, therefore it cannot recursively update itself: [] Trigger.NALeadsWeb2LeadCurrencyChange: line 19, column 2: [] Class.NALeadsWeb2LeadCurrencyChanger.myUnitTest: line 15, column 4 External entry point Cumulative resource usage: Resource usage for namespace: (default) Number of SOQL queries: 2 out of 100 Number of query rows: 2 out of 500 Number of SOSL queries: 0 out of 20 Number of DML statements: 2 out of 100 Number of DML rows: 2 out of 500 Number of script statements: 4 out of 200000 Maximum heap size: 0 out of 1000000 Number of callouts: 0 out of 10 Number of Email Invocations: 0 out of 10 Number of fields describes: 0 out of 10 Number of record type describes: 0 out of 10 Number of child relationships describes: 0 out of 10 Number of picklist describes: 0 out of 10 Number of future calls: 0 out of 10 Number of find similar calls: 0 out of 10 Number of System.runAs() invocations: 0 out of 20 Total email recipients queued to be sent : 0 Stack frame variables and sizes: Frame0 *** Ending Test NALeadsWeb2LeadCurrencyChanger.static testMethod void myUnitTest()

 


 


 

Best Answer chosen by Admin (Salesforce Developers) 
SuperfellSuperfell
You have a before update trigger, so you should not be calling update, you should just update the records in the trigger.new collection. (you should also pull the queries out of the loops, and i don't think you even need the 2nd query)

All Answers

SuperfellSuperfell
You have a before update trigger, so you should not be calling update, you should just update the records in the trigger.new collection. (you should also pull the queries out of the loops, and i don't think you even need the 2nd query)
This was selected as the best answer
MattyDHLMattyDHL

Thanks for your help, im done for the day but will clear up the code tomorrow.

 

I really dont think im cut out for this programming stuff, but everyday I am learning more.


Again thanks!!!!

globalsfdcglobalsfdc

public with sharing class CustomClone_Cntrllr1
{
    public PageReference cloneData()
    {
        if(newAccSer == null || newAccSer == '')
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Enter New Account Service Name'));
            return null;   
        }
        else
        {
        RAN_Account_Service_Fee__c clAccSer = new RAN_Account_Service_Fee__c();
        List<RAN_Local_Subsidiary__c> countFee = new List<RAN_Local_Subsidiary__c>();
        List<RAN_Local_Subsidiary__c> clCountryFee = new List<RAN_Local_Subsidiary__c>();
        Map<id,List<RAN_Procedure__c>> mapProcs = new Map<id,List<RAN_Procedure__c>>();
        List<id> scfids = new List<id>();
        Map<id,id> oldNew = new Map<id,id>();
        List<RAN_Procedure__c> clProcs = new List<RAN_Procedure__c>();
        List<RAN_Procedure__c> procs = new List<RAN_Procedure__c>();
        List<RAN_Procedure__c> procs1 = new List<RAN_Procedure__c>();
        String soqlAcc = getCreatableFieldsSOQL('RAN_Account_Service_Fee__c','id=:aid');
        ranAccountService = (RAN_Account_Service_Fee__c)Database.query(soqlAcc);
        Integer k = ranAccountService.Fee_Calculation_Date__c.daysBetween(Date.Today());
        clAccSer = ranAccountService.clone(false,true);
        if(k>180)
        {
            clAccSer.Start_Date__c = clAccSer.Start_Date__c.addDays(365);
            clAccSer.End_Date__c = clAccSer.End_Date__c.addDays(365);
            clAccSer.Fee_Calculation_Date__c = clAccSer.Fee_Calculation_Date__c.addDays(365);
        }
        clAccSer.Status__c = 'Draft';
        clAccSer.Date_Closed__c = null;
        clAccSer.Actual_Servicing_Fee__c = null;
        clAccSer.Name = newAccSer;
        insert clAccSer;
        Map<string,string> m1 = new Map<string,string>(); 
        Map<string,Id> m2 = new Map<string,Id>();    
      //  List<string> cont = new list<string>();    
        for(WrapperCountryFees wc : selCountryFees )
        {
            if(wc.check == true)
            {
               scfids.add(wc.selCountry.id);
           //    m1.put(wc.selCountry.name,wc.selCountry.id);
             //  cont.add(wc.selCountry.New_Pricing_Country__c);      
              m2.put(wc.selCountry.name.substring(5),wc.selCountry.id); 
              system.debug('******country**'+m2);                 
            }
        }
           List<string> cont1 = new List<string>();   
           List<AggregateResult> aggrs =[select max(Fiscal_Year__c) nm,Country__c pc from RAN_Pricing_Model__c where Country__c in :m2.keyset() group by Country__c];
           for(Aggregateresult rs :aggrs )
           {
                  m1.put(string.valueof(rs.get('pc')),string.valueof(rs.get('nm')));
         //         cont.add(string.valueof(rs.get('pc'))+string.valueof(rs.get('nm')));
                  cont1.add(string.valueof(rs.get('nm'))+' '+string.valueof(rs.get('pc')));
        //          system.debug('******cont**'+cont);
                }
          Map<id,string> m3 = new Map<id,string>();
          Map<string,id> m4 = new Map<string,id>();
         for(RAN_Pricing_Model__c rp:      [ select id,Country__c,name from RAN_Pricing_Model__c where name in :cont1])
         {
            m3.put(rp.id,rp.name);
            m4.put(rp.Country__c,rp.id);       
         }
          system.debug('******m3**'+m3);
          system.debug('******m3**'+m4);
         
        String soqlCf = getCreatableFieldsSOQL('RAN_Local_Subsidiary__c','id in :scfids');
        countFee = (List<RAN_Local_Subsidiary__c>)Database.query(soqlCf);
        String soqlPr = getCreatableFieldsSOQL('RAN_Procedure__c','RAN_Local_Subsidiary__c in :scfids');
        procs = (List<RAN_Procedure__c>)Database.query(soqlPr);
        for(RAN_Local_Subsidiary__c rc : countFee)
        {
            RAN_Local_Subsidiary__c c = new RAN_Local_Subsidiary__c();
            //procs.clear();
            List<RAN_Procedure__c> prs = new List<RAN_Procedure__c>();          
            c = rc.clone(false,true);
            oldNew.put(rc.id,c.id);
            //String soqlPr = getCreatableFieldsSOQL('RAN_Procedure__c','RAN_Local_Subsidiary__c = :rc.id');
            //procs = (List<RAN_Procedure__c>)Database.query(soqlPr);
           
            c.Account_Service_Fee__c = clAccSer.id;
            c.Pricing_Country_Reference__c = m4.get(rc.name.substring(5));
            c.name=m3.get(c.Pricing_Country_Reference__c);
            clCountryFee.add(c);
        }
        /*List<RAN_Pricing_Model__c> pm = [select id,name,Fiscal_Year__c,Region__c from RAN_Pricing_Model__c where Country__c in :SCountryvalues order by Fiscal_Year__c desc limit :SCountryvalues.size()];
        for(RAN_Pricing_Model__c p : pm)
        {
           RAN_Local_Subsidiary__c cf = new RAN_Local_Subsidiary__c();
           cf.Name = p.Name;
           cf.Account_Service_Fee__c = rid ;
           cf.Pricing_Country_Reference__c = p.id;
           cf.Client_Visit_Hours__c = 4;
           mapPm.put(p.Name,p.Region__c);
           countryFees.add(cf);   
        }*/
        insert clCountryFee;
        for(RAN_Procedure__c rp : procs )
            {
                RAN_Procedure__c p = new RAN_Procedure__c();
                p = rp.clone(false,true);
                Procs1.add(p);
                /*if(rc.id == p.RAN_Local_Subsidiary__c)
                {
                    p.RAN_Local_Subsidiary__c =c.id;
                    clProcs.add(p);
                } */                            
            }
            //mapProcs.put(rc.id , prs);
        Integer i = 0;
        for(RAN_Local_Subsidiary__c rc : countFee)
        {
            for(RAN_Procedure__c p : procs1)
            {
                if(rc.id == p.RAN_Local_Subsidiary__c)
                {
                    p.RAN_Local_Subsidiary__c = clCountryFee.get(i).id;
                    clProcs.add(p);
                }
            }
            i++;
        }
        insert clProcs;
        return new Apexpages.standardcontroller(clAccSer).edit();
        }
    }


    public PageReference cancel()
    {
       
        return new Apexpages.standardcontroller(ranAccountService).view();
    }

    public id aid;
    public String newAccSer{get;set;}
    public List<WrapperCountryFees> selCountryFees{get;set;}
    public List<RAN_Local_Subsidiary__c> countryFees{get;set;}
    public RAN_Account_Service_Fee__c ranAccountService{get;set;}
   
    public CustomClone_Cntrllr1(ApexPages.StandardController controller)
    {
        aid = ApexPages.currentpage().getParameters().get('id');
        selCountryFees = new List<WrapperCountryFees>();
        ranAccountService = [select id from RAN_Account_Service_Fee__c  where id = :aid];
        String query = 'Select id,Name,New_Pricing_Country__c from RAN_Local_Subsidiary__c where Account_Service_Fee__c = :aid';
        countryFees = Database.Query(query);
        List<RAN_Local_Subsidiary__c> qrc = new List<RAN_Local_Subsidiary__c>();
        for(RAN_Local_Subsidiary__c rc : countryFees)
         {
                qrc.add(rc);           
         }   
         qrc.sort();
        for(RAN_Local_Subsidiary__c rc : qrc)
         {
             WrapperCountryFees wcf = new WrapperCountryFees();
             wcf.selCountry = rc;
             wcf.check = false;
             wcf.cfid = rc.id;            
             selCountryFees.add(wcf);
         }   
    }
   
    public class WrapperCountryFees
    {
        public RAN_Local_Subsidiary__c selCountry{get;set;}
        public id cfid{get;set;}
        public boolean check{get;set;}
    }
   
    public PageReference clearAll()
    {
        List<WrapperCountryFees> cfc = new List<WrapperCountryFees>();
        cfc.addAll(selCountryFees);
        selCountryFees.clear();
        for(WrapperCountryFees wcf : cfc)
        {
            wcf.check = false;
            selCountryFees.add(wcf);
        }
        return null;
    }
   
    public PageReference selectAll()
    {
        List<WrapperCountryFees> cfs = new List<WrapperCountryFees>();
        cfs.addAll(selCountryFees);
        selCountryFees.clear();
        for(WrapperCountryFees wcf : cfs)
        {
            wcf.check = true;
            selCountryFees.add(wcf);
        }
        return null;
    }
    public  string getCreatableFieldsSOQL(String objectName, String whereClause)
    {
        String selects = '';
        if (whereClause == null || whereClause == ''){ return null; }
        Map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();
        list<string> selectFields = new list<string>();
        if (fMap != null)
        {
            for (Schema.SObjectField ft : fMap.values())
            { // loop through all field tokens (ft)
                Schema.DescribeFieldResult fd = ft.getDescribe(); // describe each field (fd)
                if (fd.isCreateable())
                { // field is creatable
                    selectFields.add(fd.getName());
                }
            }
        }
        if (!selectFields.isEmpty())
        {
            for (string s:selectFields)
            {
                selects += s + ',';
            }
            if (selects.endsWith(','))
            {
                selects = selects.substring(0,selects.lastIndexOf(','));
            }
        }
        return  'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause;
    }
}

 

 

globalsfdcglobalsfdc

public with sharing class CustomClone_Cntrllr1
{
    public PageReference cloneData()
    {
        if(newAccSer == null & newAccSer == '')
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Enter New Account Service Name'));
            return null;   
        }
        else
        {
        RAN_Account_Service_Fee__c clAccSer = new RAN_Account_Service_Fee__c();
        List<RAN_Local_Subsidiary__c> countFee = new List<RAN_Local_Subsidiary__c>();
        List<RAN_Local_Subsidiary__c> clCountryFee = new List<RAN_Local_Subsidiary__c>();
        Map<id,List<RAN_Procedure__c>> mapProcs = new Map<id,List<RAN_Procedure__c>>();
        List<id> scfids = new List<id>();
        Map<id,id> oldNew = new Map<id,id>();
        List<RAN_Procedure__c> clProcs = new List<RAN_Procedure__c>();
        List<RAN_Procedure__c> procs = new List<RAN_Procedure__c>();
        List<RAN_Procedure__c> procs1 = new List<RAN_Procedure__c>();
        String soqlAcc = getCreatableFieldsSOQL('RAN_Account_Service_Fee__c','id=:aid');
        ranAccountService = (RAN_Account_Service_Fee__c)Database.query(soqlAcc);
        Integer k = ranAccountService.Fee_Calculation_Date__c.daysBetween(Date.Today());
        clAccSer = ranAccountService.clone(false,true);
        if(k>180)
        {
            clAccSer.Start_Date__c = clAccSer.Start_Date__c.addDays(365);
            clAccSer.End_Date__c = clAccSer.End_Date__c.addDays(365);
            clAccSer.Fee_Calculation_Date__c = clAccSer.Fee_Calculation_Date__c.addDays(365);
        }
        clAccSer.Status__c = 'Draft';
        clAccSer.Date_Closed__c = null;
        clAccSer.Actual_Servicing_Fee__c = null;
        clAccSer.Name = newAccSer;
        insert clAccSer;
        Map<string,string> m1 = new Map<string,string>(); 
        Map<string,Id> m2 = new Map<string,Id>();    
      //  List<string> cont = new list<string>();    
        for(WrapperCountryFees wc : selCountryFees )
        {
            if(wc.check == true)
            {
               scfids.add(wc.selCountry.id);
           //    m1.put(wc.selCountry.name,wc.selCountry.id);
             //  cont.add(wc.selCountry.New_Pricing_Country__c);      
              m2.put(wc.selCountry.name.substring(5),wc.selCountry.id); 
              system.debug('******country**'+m2);                 
            }
        }
           List<string> cont1 = new List<string>();   
           List<AggregateResult> aggrs =[select max(Fiscal_Year__c) nm,Country__c pc from RAN_Pricing_Model__c where Country__c in :m2.keyset() group by Country__c];
           for(Aggregateresult rs :aggrs )
           {
                  m1.put(string.valueof(rs.get('pc')),string.valueof(rs.get('nm')));
         //         cont.add(string.valueof(rs.get('pc'))+string.valueof(rs.get('nm')));
                  cont1.add(string.valueof(rs.get('nm'))+' '+string.valueof(rs.get('pc')));
        //          system.debug('******cont**'+cont);
                }
          Map<id,string> m3 = new Map<id,string>();
          Map<string,id> m4 = new Map<string,id>();
         for(RAN_Pricing_Model__c rp:      [ select id,Country__c,name from RAN_Pricing_Model__c where name in :cont1])
         {
            m3.put(rp.id,rp.name);
            m4.put(rp.Country__c,rp.id);       
         }
          system.debug('******m3**'+m3);
          system.debug('******m3**'+m4);
         
        String soqlCf = getCreatableFieldsSOQL('RAN_Local_Subsidiary__c','id in :scfids');
        countFee = (List<RAN_Local_Subsidiary__c>)Database.query(soqlCf);
        String soqlPr = getCreatableFieldsSOQL('RAN_Procedure__c','RAN_Local_Subsidiary__c in :scfids');
        procs = (List<RAN_Procedure__c>)Database.query(soqlPr);
        for(RAN_Local_Subsidiary__c rc : countFee)
        {
            RAN_Local_Subsidiary__c c = new RAN_Local_Subsidiary__c();
            //procs.clear();
            List<RAN_Procedure__c> prs = new List<RAN_Procedure__c>();          
            c = rc.clone(false,true);
            oldNew.put(rc.id,c.id);
            //String soqlPr = getCreatableFieldsSOQL('RAN_Procedure__c','RAN_Local_Subsidiary__c = :rc.id');
            //procs = (List<RAN_Procedure__c>)Database.query(soqlPr);
           
            c.Account_Service_Fee__c = clAccSer.id;
            c.Pricing_Country_Reference__c = m4.get(rc.name.substring(5));
            c.name=m3.get(c.Pricing_Country_Reference__c);
            clCountryFee.add(c);
        }
        /*List<RAN_Pricing_Model__c> pm = [select id,name,Fiscal_Year__c,Region__c from RAN_Pricing_Model__c where Country__c in :SCountryvalues order by Fiscal_Year__c desc limit :SCountryvalues.size()];
        for(RAN_Pricing_Model__c p : pm)
        {
           RAN_Local_Subsidiary__c cf = new RAN_Local_Subsidiary__c();
           cf.Name = p.Name;
           cf.Account_Service_Fee__c = rid ;
           cf.Pricing_Country_Reference__c = p.id;
           cf.Client_Visit_Hours__c = 4;
           mapPm.put(p.Name,p.Region__c);
           countryFees.add(cf);   
        }*/
        insert clCountryFee;
        for(RAN_Procedure__c rp : procs )
            {
                RAN_Procedure__c p = new RAN_Procedure__c();
                p = rp.clone(false,true);
                Procs1.add(p);
                /*if(rc.id == p.RAN_Local_Subsidiary__c)
                {
                    p.RAN_Local_Subsidiary__c =c.id;
                    clProcs.add(p);
                } */                            
            }
            //mapProcs.put(rc.id , prs);
        Integer i = 0;
        for(RAN_Local_Subsidiary__c rc : countFee)
        {
            for(RAN_Procedure__c p : procs1)
            {
                if(rc.id == p.RAN_Local_Subsidiary__c)
                {
                    p.RAN_Local_Subsidiary__c = clCountryFee.get(i).id;
                    clProcs.add(p);
                }
            }
            i++;
        }
        insert clProcs;
        return new Apexpages.standardcontroller(clAccSer).edit();
        }
    }


    public PageReference cancel()
    {
       
        return new Apexpages.standardcontroller(ranAccountService).view();
    }

    public id aid;
    public String newAccSer{get;set;}
    public List<WrapperCountryFees> selCountryFees{get;set;}
    public List<RAN_Local_Subsidiary__c> countryFees{get;set;}
    public RAN_Account_Service_Fee__c ranAccountService{get;set;}
   
    public CustomClone_Cntrllr1(ApexPages.StandardController controller)
    {
        aid = ApexPages.currentpage().getParameters().get('id');
        selCountryFees = new List<WrapperCountryFees>();
        ranAccountService = [select id from RAN_Account_Service_Fee__c  where id = :aid];
        String query = 'Select id,Name,New_Pricing_Country__c from RAN_Local_Subsidiary__c where Account_Service_Fee__c = :aid';
        countryFees = Database.Query(query);
        List<RAN_Local_Subsidiary__c> qrc = new List<RAN_Local_Subsidiary__c>();
        for(RAN_Local_Subsidiary__c rc : countryFees)
         {
                qrc.add(rc);           
         }   
         qrc.sort();
        for(RAN_Local_Subsidiary__c rc : qrc)
         {
             WrapperCountryFees wcf = new WrapperCountryFees();
             wcf.selCountry = rc;
             wcf.check = false;
             wcf.cfid = rc.id;            
             selCountryFees.add(wcf);
         }   
    }
   
    public class WrapperCountryFees
    {
        public RAN_Local_Subsidiary__c selCountry{get;set;}
        public id cfid{get;set;}
        public boolean check{get;set;}
    }
   
    public PageReference clearAll()
    {
        List<WrapperCountryFees> cfc = new List<WrapperCountryFees>();
        cfc.addAll(selCountryFees);
        selCountryFees.clear();
        for(WrapperCountryFees wcf : cfc)
        {
            wcf.check = false;
            selCountryFees.add(wcf);
        }
        return null;
    }
   
    public PageReference selectAll()
    {
        List<WrapperCountryFees> cfs = new List<WrapperCountryFees>();
        cfs.addAll(selCountryFees);
        selCountryFees.clear();
        for(WrapperCountryFees wcf : cfs)
        {
            wcf.check = true;
            selCountryFees.add(wcf);
        }
        return null;
    }
    public  string getCreatableFieldsSOQL(String objectName, String whereClause)
    {
        String selects = '';
        if (whereClause == null || whereClause == ''){ return null; }
        Map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();
        list<string> selectFields = new list<string>();
        if (fMap != null)
        {
            for (Schema.SObjectField ft : fMap.values())
            { // loop through all field tokens (ft)
                Schema.DescribeFieldResult fd = ft.getDescribe(); // describe each field (fd)
                if (fd.isCreateable())
                { // field is creatable
                    selectFields.add(fd.getName());
                }
            }
        }
        if (!selectFields.isEmpty())
        {
            for (string s:selectFields)
            {
                selects += s + ',';
            }
            if (selects.endsWith(','))
            {
                selects = selects.substring(0,selects.lastIndexOf(','));
            }
        }
        return  'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause;
    }
}

 

 

globalsfdcglobalsfdc

am getting below error:

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, grantPublicGroupAccess: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [User/Group]: [User/Group] Class.RANShareController.grantServiceFeeShareAccess: line 22, column 1 Trigger.grantPublicGroupAccess: line 76, column 1:

 

Thanks in advance.....


globalsfdc wrote:

public with sharing class CustomClone_Cntrllr1
{
    public PageReference cloneData()
    {
        if(newAccSer == null || newAccSer == '')
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Enter New Account Service Name'));
            return null;   
        }
        else
        {
        RAN_Account_Service_Fee__c clAccSer = new RAN_Account_Service_Fee__c();
        List<RAN_Local_Subsidiary__c> countFee = new List<RAN_Local_Subsidiary__c>();
        List<RAN_Local_Subsidiary__c> clCountryFee = new List<RAN_Local_Subsidiary__c>();
        Map<id,List<RAN_Procedure__c>> mapProcs = new Map<id,List<RAN_Procedure__c>>();
        List<id> scfids = new List<id>();
        Map<id,id> oldNew = new Map<id,id>();
        List<RAN_Procedure__c> clProcs = new List<RAN_Procedure__c>();
        List<RAN_Procedure__c> procs = new List<RAN_Procedure__c>();
        List<RAN_Procedure__c> procs1 = new List<RAN_Procedure__c>();
        String soqlAcc = getCreatableFieldsSOQL('RAN_Account_Service_Fee__c','id=:aid');
        ranAccountService = (RAN_Account_Service_Fee__c)Database.query(soqlAcc);
        Integer k = ranAccountService.Fee_Calculation_Date__c.daysBetween(Date.Today());
        clAccSer = ranAccountService.clone(false,true);
        if(k>180)
        {
            clAccSer.Start_Date__c = clAccSer.Start_Date__c.addDays(365);
            clAccSer.End_Date__c = clAccSer.End_Date__c.addDays(365);
            clAccSer.Fee_Calculation_Date__c = clAccSer.Fee_Calculation_Date__c.addDays(365);
        }
        clAccSer.Status__c = 'Draft';
        clAccSer.Date_Closed__c = null;
        clAccSer.Actual_Servicing_Fee__c = null;
        clAccSer.Name = newAccSer;
        insert clAccSer;
        Map<string,string> m1 = new Map<string,string>(); 
        Map<string,Id> m2 = new Map<string,Id>();    
      //  List<string> cont = new list<string>();    
        for(WrapperCountryFees wc : selCountryFees )
        {
            if(wc.check == true)
            {
               scfids.add(wc.selCountry.id);
           //    m1.put(wc.selCountry.name,wc.selCountry.id);
             //  cont.add(wc.selCountry.New_Pricing_Country__c);      
              m2.put(wc.selCountry.name.substring(5),wc.selCountry.id); 
              system.debug('******country**'+m2);                 
            }
        }
           List<string> cont1 = new List<string>();   
           List<AggregateResult> aggrs =[select max(Fiscal_Year__c) nm,Country__c pc from RAN_Pricing_Model__c where Country__c in :m2.keyset() group by Country__c];
           for(Aggregateresult rs :aggrs )
           {
                  m1.put(string.valueof(rs.get('pc')),string.valueof(rs.get('nm')));
         //         cont.add(string.valueof(rs.get('pc'))+string.valueof(rs.get('nm')));
                  cont1.add(string.valueof(rs.get('nm'))+' '+string.valueof(rs.get('pc')));
        //          system.debug('******cont**'+cont);
                }
          Map<id,string> m3 = new Map<id,string>();
          Map<string,id> m4 = new Map<string,id>();
         for(RAN_Pricing_Model__c rp:      [ select id,Country__c,name from RAN_Pricing_Model__c where name in :cont1])
         {
            m3.put(rp.id,rp.name);
            m4.put(rp.Country__c,rp.id);       
         }
          system.debug('******m3**'+m3);
          system.debug('******m3**'+m4);
         
        String soqlCf = getCreatableFieldsSOQL('RAN_Local_Subsidiary__c','id in :scfids');
        countFee = (List<RAN_Local_Subsidiary__c>)Database.query(soqlCf);
        String soqlPr = getCreatableFieldsSOQL('RAN_Procedure__c','RAN_Local_Subsidiary__c in :scfids');
        procs = (List<RAN_Procedure__c>)Database.query(soqlPr);
        for(RAN_Local_Subsidiary__c rc : countFee)
        {
            RAN_Local_Subsidiary__c c = new RAN_Local_Subsidiary__c();
            //procs.clear();
            List<RAN_Procedure__c> prs = new List<RAN_Procedure__c>();          
            c = rc.clone(false,true);
            oldNew.put(rc.id,c.id);
            //String soqlPr = getCreatableFieldsSOQL('RAN_Procedure__c','RAN_Local_Subsidiary__c = :rc.id');
            //procs = (List<RAN_Procedure__c>)Database.query(soqlPr);
           
            c.Account_Service_Fee__c = clAccSer.id;
            c.Pricing_Country_Reference__c = m4.get(rc.name.substring(5));
            c.name=m3.get(c.Pricing_Country_Reference__c);
            clCountryFee.add(c);
        }
        /*List<RAN_Pricing_Model__c> pm = [select id,name,Fiscal_Year__c,Region__c from RAN_Pricing_Model__c where Country__c in :SCountryvalues order by Fiscal_Year__c desc limit :SCountryvalues.size()];
        for(RAN_Pricing_Model__c p : pm)
        {
           RAN_Local_Subsidiary__c cf = new RAN_Local_Subsidiary__c();
           cf.Name = p.Name;
           cf.Account_Service_Fee__c = rid ;
           cf.Pricing_Country_Reference__c = p.id;
           cf.Client_Visit_Hours__c = 4;
           mapPm.put(p.Name,p.Region__c);
           countryFees.add(cf);   
        }*/
        insert clCountryFee;
        for(RAN_Procedure__c rp : procs )
            {
                RAN_Procedure__c p = new RAN_Procedure__c();
                p = rp.clone(false,true);
                Procs1.add(p);
                /*if(rc.id == p.RAN_Local_Subsidiary__c)
                {
                    p.RAN_Local_Subsidiary__c =c.id;
                    clProcs.add(p);
                } */                            
            }
            //mapProcs.put(rc.id , prs);
        Integer i = 0;
        for(RAN_Local_Subsidiary__c rc : countFee)
        {
            for(RAN_Procedure__c p : procs1)
            {
                if(rc.id == p.RAN_Local_Subsidiary__c)
                {
                    p.RAN_Local_Subsidiary__c = clCountryFee.get(i).id;
                    clProcs.add(p);
                }
            }
            i++;
        }
        insert clProcs;
        return new Apexpages.standardcontroller(clAccSer).edit();
        }
    }


    public PageReference cancel()
    {
       
        return new Apexpages.standardcontroller(ranAccountService).view();
    }

    public id aid;
    public String newAccSer{get;set;}
    public List<WrapperCountryFees> selCountryFees{get;set;}
    public List<RAN_Local_Subsidiary__c> countryFees{get;set;}
    public RAN_Account_Service_Fee__c ranAccountService{get;set;}
   
    public CustomClone_Cntrllr1(ApexPages.StandardController controller)
    {
        aid = ApexPages.currentpage().getParameters().get('id');
        selCountryFees = new List<WrapperCountryFees>();
        ranAccountService = [select id from RAN_Account_Service_Fee__c  where id = :aid];
        String query = 'Select id,Name,New_Pricing_Country__c from RAN_Local_Subsidiary__c where Account_Service_Fee__c = :aid';
        countryFees = Database.Query(query);
        List<RAN_Local_Subsidiary__c> qrc = new List<RAN_Local_Subsidiary__c>();
        for(RAN_Local_Subsidiary__c rc : countryFees)
         {
                qrc.add(rc);           
         }   
         qrc.sort();
        for(RAN_Local_Subsidiary__c rc : qrc)
         {
             WrapperCountryFees wcf = new WrapperCountryFees();
             wcf.selCountry = rc;
             wcf.check = false;
             wcf.cfid = rc.id;            
             selCountryFees.add(wcf);
         }   
    }
   
    public class WrapperCountryFees
    {
        public RAN_Local_Subsidiary__c selCountry{get;set;}
        public id cfid{get;set;}
        public boolean check{get;set;}
    }
   
    public PageReference clearAll()
    {
        List<WrapperCountryFees> cfc = new List<WrapperCountryFees>();
        cfc.addAll(selCountryFees);
        selCountryFees.clear();
        for(WrapperCountryFees wcf : cfc)
        {
            wcf.check = false;
            selCountryFees.add(wcf);
        }
        return null;
    }
   
    public PageReference selectAll()
    {
        List<WrapperCountryFees> cfs = new List<WrapperCountryFees>();
        cfs.addAll(selCountryFees);
        selCountryFees.clear();
        for(WrapperCountryFees wcf : cfs)
        {
            wcf.check = true;
            selCountryFees.add(wcf);
        }
        return null;
    }
    public  string getCreatableFieldsSOQL(String objectName, String whereClause)
    {
        String selects = '';
        if (whereClause == null || whereClause == ''){ return null; }
        Map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();
        list<string> selectFields = new list<string>();
        if (fMap != null)
        {
            for (Schema.SObjectField ft : fMap.values())
            { // loop through all field tokens (ft)
                Schema.DescribeFieldResult fd = ft.getDescribe(); // describe each field (fd)
                if (fd.isCreateable())
                { // field is creatable
                    selectFields.add(fd.getName());
                }
            }
        }
        if (!selectFields.isEmpty())
        {
            for (string s:selectFields)
            {
                selects += s + ',';
            }
            if (selects.endsWith(','))
            {
                selects = selects.substring(0,selects.lastIndexOf(','));
            }
        }
        return  'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause;
    }
}