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
Yoni LegacyYoni Legacy 

Apex class deletion is not working

Hi,

I created an apex class to delete Account List record which has no Account List Items when I execute the class, it's not deleting the Account List with no Account List Item records.

Objects involved.

Account_List_vod__c - is the master of object Account List Item (Account_List_Item_vod__c)

Affiliation_vod__c - this object has no relation at all to Account List and Account List Item objects.


Requirements:

1. Get all the active users with Profile name that contains Eisai_Epilepsy or Eisai_PrimaryCare then order by Profile name.
2. Put all the active result query to a set.
3. Query all Account List records where ownerId is in the Active user set.
4. Iterate or loop on the Account List records, check if the Account_List_Item_Count__c field is less than 1 (No account list item records), then add it to a list named accListToDelete.
5. Lastly, delete all the records inside accListToDelete.

I think my logic is partly correct but I am just new in apex coding. Actually, this is the first time I tried to code.

Below is the actual code
.Delete Class


Actual code:

public class Eisai_AccountListDeletion_cls {
    Set<Id> userIdsSet = new Set<Id>();
    List<User> activeUSerList;
    List<Account_List_vod__c> accListRecsList;
    List<Account_List_Item_vod__c> accListItem;
    List<Account_List_vod__c> accListToDelete = new List<Account_List_vod__c>();
   
    //1st block
    public Set<Id> getActiveUserIds(){
       
            activeUSerList = new List<User>([SELECT Id,Profile_Name_esi__c
                                             FROM User
                                             WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                             AND IsActive = TRUE ORDER BY Profile_Name_vod__c]);
       
            for(User userIds : activeUSerList){
                userIdsSet.add(userIds.Id);
            }
        System.debug('User id: ' + userIdsSet);
        return userIdsSet;
    }//end of 1st block
   
    //2nd block
    public void getAccListRecords(){
       
    Integer count = 1; 
    accListRecsList = new List<Account_List_vod__c>([SELECT Id, Name, Icon_Name_vod__c, Account_List_Item_Count__c
                                                    FROM Account_List_vod__c
                                                    WHERE Name ='HO_RADY\'S CHILDREN\'S UCSD' AND OwnerId In: userIdsSet]); 
       
            for(Account_List_vod__c accListRec : accListRecsList){
                    if(Integer.valueOf(accListRec.Account_List_Item_Count__c) < count){
                        accListToDelete.add(accListRec);
                    }else{
                        System.debug('-----Cannot delete Account List record as it has Account List Item records-----');
                    }
            }
        delete accListToDelete;
    }//end of 2nd block
}
 
Thank you.
Marion
Best Answer chosen by Yoni Legacy
badibadi
Okay, So we need to trace where its going wrong. I would do the following steps

1. Make you executing these lines

    
Eisai_AccountListDeletion_cls eDel= new  Eisai_AccountListDeletion_cls();
eDel.getAccListRecords();
2.  Modify the try and catch statements again 
try{
       delete accListToDelete;
        System.debug('I executed  '+accListToDelete.size() + ' number of records');
    }catch(DmlException e){
        System.debug(e.getdmlMessage(0));
    }catch(Exception e) {
       System.debug(e.getMessage());
    }

So now we have 4 debug statements, The first debug before the try/catch block must be executed and look for any debug statements within the try/catch block. 

If the debug in the try executed. Then make sure you have delete permissions for the object.

Hope this helps

All Answers

badibadi
Hello,

I have made some changes to your class, hope it helps
public class Eisai_AccountListDeletion_cls {
    Set<Id> userIdsSet = new Set<Id>();
    List<User> activeUSerList;
    List<Account_List_vod__c> accListRecsList;
    //List<Account_List_Item_vod__c> accListItem; // I have commented this line as I do not see it referenced anywhere
    List<Account_List_vod__c> accListToDelete = new List<Account_List_vod__c>();
   
    //1st block - Changed this to be the constructor 
    public Eisai_AccountListDeletion_cls(){
       activeUSerList = [SELECT Id,Profile_Name_esi__c
                                FROM User
                                WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                AND IsActive = TRUE ORDER BY Profile_Name_vod__c];
       
            for(User userIds : activeUSerList){
                userIdsSet.add(userIds.Id);
            }
        System.debug('User id: ' + userIdsSet);
    }//end of 1st block
   
    //2nd block
    public void getAccListRecords(){
       
    Integer count = 1; 
    // you can also write the following block this way
        
    /******* option 1 - THis query will return only the records which have less than 1 list items
		accListRecsList =[SELECT Id, Name, Icon_Name_vod__c, Account_List_Item_Count__c
                                                    FROM Account_List_vod__c
                                                    WHERE Name ='HO_RADY\'S CHILDREN\'S UCSD' AND Account_List_Item_Count__c < 1 AND OwnerId In: userIdsSet]; 
     ********/
    // option 2 Start - or you can use your code if you need to do something with the records which have more than 1 list item
    accListRecsList = [SELECT Id, Name, Icon_Name_vod__c, Account_List_Item_Count__c
                                                    FROM Account_List_vod__c
                                                    WHERE Name ='HO_RADY\'S CHILDREN\'S UCSD' AND OwnerId In: userIdsSet]; 
       
            for(Account_List_vod__c accListRec : accListRecsList){
                    if(Integer.valueOf(accListRec.Account_List_Item_Count__c) < count){
                        accListToDelete.add(accListRec);
                    }else{
                        System.debug('-----Cannot delete Account List record as it has Account List Item records-----');
                    }
            }
   //option 2 end
        
          delete accListToDelete;
    }//end of 2nd block
}

 
Abdul RazzaqAbdul Razzaq
I think badi has done it. If still, try writing debug statement in if-loop and check values of accListToDelete. 
Yoni LegacyYoni Legacy
@Badi question, does apex class is required to have a contructor or main class like java? Another question, how do you paste the entire code like that? Seems like a screnn shot. Is that notepad++?

Yes I added this line already.
accListRecsList =[SELECT Id, Name, Icon_Name_vod__c, Account_List_Item_Count__c
                                                   FROM Account_List_vod__c
                                                    WHERE Name ='HO_RADY\'S CHILDREN\'S UCSD' AND Account_List_Item_Count__c < 1 AND OwnerId In: userIdsSet];
Yoni LegacyYoni Legacy
@Adbul Razzaq
I will let you know once the code of Badi works or not.. Thanks
Yoni LegacyYoni Legacy
@Badi and @Adbul

This is the exact class which I executed, but the Account List records with no Account List Item was not deleted.


public class Eisai_AccountListDeletion_cls {
    Set<Id> userIdsSet = new Set<Id>();
    List<User> activeUSerList;
    List<Account_List_vod__c> accListRecsList;
    List<Account_List_vod__c> accListToDelete = new List<Account_List_vod__c>();
   
    //1st block - Changed this to be the constructor 
    public Eisai_AccountListDeletion_cls(){
       activeUSerList = [SELECT Id,Profile_Name_esi__c
                                FROM User
                                WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                AND IsActive = TRUE ORDER BY Profile_Name_vod__c];
       
            for(User userIds : activeUSerList){
                userIdsSet.add(userIds.Id);
            }
        System.debug('User id: ' + userIdsSet);
    }//end of 1st block
   
    //2nd block
    public void getAccListRecords(){
       
     accListRecsList = [SELECT Id, Name, Icon_Name_vod__c, Account_List_Item_Count__c
                                                    FROM Account_List_vod__c
                                                    WHERE Name ='HO_RADY\'S CHILDREN\'S UCSD' 
                                                    AND Account_List_Item_Count__c < 1 
                                                    AND OwnerId In: userIdsSet]; 
                                                    
    System.debug('List of Account List Records to delete ' + accListRecsList);                                               
       
            for(Account_List_vod__c accListRec : accListRecsList){
                        accListToDelete.add(accListRec);
                        
            }
         delete accListToDelete;
    }//end of 2nd block
}

Anythoughts?

Thank you to both of you, if you can only be my mentor then I'll be happy.

Marion
badibadi
You do not need to explicitly have a constructor but in this case we use it.

To add code, click on the <> button in the rich text editor and add your code.

For delete not working,

did you check the debug logs to make sure there are records in the accListToDelete List?

Replace 
 
delete accListToDelete;

with 
 
try{
   delete accListToDelete;
}catch(DmlException e){
    System.debug(e.getdmlMessage(0));
}catch(Exception e) {
   System.debug(e.getMessage());
}

let me know if you are getting any errors 
Yoni LegacyYoni Legacy
Badi,

Still it's not working and not giving any error message or system debug logs.. 

I believe the 1st block is working as the 188 active users are returning.

Here is the edited code.

public class Eisai_AccountListDeletion_cls {
    Set<Id> userIdsSet = new Set<Id>();
    List<User> activeUSerList;
    List<Account_List_vod__c> accListRecsList;
    List<Account_List_vod__c> accListToDelete = new List<Account_List_vod__c>();
   
    //1st block - Changed this to be the constructor 
    public Eisai_AccountListDeletion_cls(){
       activeUSerList = [SELECT Id,Profile_Name_esi__c
                                FROM User
                                WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                AND IsActive = TRUE ORDER BY Profile_Name_vod__c];
       
            for(User userIds : activeUSerList){
                userIdsSet.add(userIds.Id);
            }
        System.debug('User id: ' + userIdsSet);
    }//end of 1st block
   
    //2nd block
    public void getAccListRecords(){
       
     accListRecsList = [SELECT Id, Name, Icon_Name_vod__c, Account_List_Item_Count__c
                                                    FROM Account_List_vod__c
                                                    WHERE Name ='HO_RADY\'S CHILDREN\'S UCSD' 
                                                    AND Account_List_Item_Count__c < 1 
                                                    AND OwnerId In: userIdsSet]; 
                                                    
    System.debug('List of Account List Records to delete ' + accListRecsList);                                               
       
            for(Account_List_vod__c accListRec : accListRecsList){
                        accListToDelete.add(accListRec);
                        
            }
    
    try{
       delete accListToDelete;
    }catch(DmlException e){
        System.debug(e.getdmlMessage(0));
    }catch(Exception e) {
       System.debug(e.getMessage());
    }

    
    }//end of 2nd block
}
Yoni LegacyYoni Legacy
How can I copy the codes with styles and number per rows? just like what you posted..
Abdul RazzaqAbdul Razzaq
you can just copy the code on the above snippet. You cannot copy the styling of it. When you hover over the snippet code, on the right side you find options 'view source', 'copy to clipboard', 'print' etc..
badibadi
Yoni,

Like Abdul said. When you copy the code from your editor it will be pain code. but when you paste that to "Add a code sample" section of the text editor and click OK and hit Answer thats when it converts to code with style and numbers. After you click Answer you need to refresh your screen to see the styles but it will be there.

About the 2nd block not working. How are you executing the code? I mean are you executing it from visualforce page or from execute anonymous window?
Yoni LegacyYoni Legacy
I'm just executing it from anonymous window.. 
badibadi
Okay, So we need to trace where its going wrong. I would do the following steps

1. Make you executing these lines

    
Eisai_AccountListDeletion_cls eDel= new  Eisai_AccountListDeletion_cls();
eDel.getAccListRecords();
2.  Modify the try and catch statements again 
try{
       delete accListToDelete;
        System.debug('I executed  '+accListToDelete.size() + ' number of records');
    }catch(DmlException e){
        System.debug(e.getdmlMessage(0));
    }catch(Exception e) {
       System.debug(e.getMessage());
    }

So now we have 4 debug statements, The first debug before the try/catch block must be executed and look for any debug statements within the try/catch block. 

If the debug in the try executed. Then make sure you have delete permissions for the object.

Hope this helps
This was selected as the best answer
Yoni LegacyYoni Legacy
Before I execute the code the line below, where should I check the logs? Is it also in the Developer console or somewhere else?

Eisai_AccountListDeletion_cls eDel= new Eisai_AccountListDeletion_cls(); eDel.getAccListRecords();
badibadi
Not exactly sure what you mean by before executing the line. But you cannot look at the logs before you execute something, If you are looking for logs for previously executed code, then if you executed directly in Developer Console then logs will be under the logs tab.

 https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_debugging_system_log_console.htm

Other option is you can set up Debug logs in Setup 

https://help.salesforce.com/HTViewHelpDoc?id=code_add_users_debug_log.htm&language=en_US
Yoni LegacyYoni Legacy
Badi,

Here is what happened, When I run the execute the entire class
Eisai_AccountListDeletion_cls eDel= new  Eisai_AccountListDeletion_cls();

It's not deleting the Account List named, HO_RADY'S CHILDREN'S UCSD. However, when I tried to execute the specific methond using 
 
Eisai_AccountListDeletion_cls eDel= new  Eisai_AccountListDeletion_cls();
eDel.getAccListRecords();

The Account List got delete.. Anythoughs? It seems that It's only reading the 1st block when executing the entire class.

 
badibadi
When you execute just 
Eisai_AccountListDeletion_cls eDel= new  Eisai_AccountListDeletion_cls();

we are instantiating a new object for that class and that will excecute whats there in the constructor. Since block 2 is not references anywhere in the constructor you need to call the method to execute it. 

You can modify your code block1 to 
public Eisai_AccountListDeletion_cls(){
       activeUSerList = [SELECT Id,Profile_Name_esi__c
                                FROM User
                                WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                AND IsActive = TRUE ORDER BY Profile_Name_vod__c];
       
            for(User userIds : activeUSerList){
                userIdsSet.add(userIds.Id);
            }
        System.debug('User id: ' + userIdsSet);
        getAccListRecords(); 
    }//end of 1st block

now as you can see, we are calling getAccListRecords() method in the constructor.
With this method you do not need to execute 2 lines of code. 
Yoni LegacyYoni Legacy
Hmmm there is strange happening now.. on the query below, I just remove the hardcoded name of Account List ('HO_RADY\'S CHILDREN\'S UCSD' ) now it's not deleting more than 1 account list with 0 account list item.
 
accListRecsList = [SELECT Id, Name, Icon_Name_vod__c, Account_List_Item_Count__c
                                                    FROM Account_List_vod__c
                                                    WHERE Name ='HO_RADY\'S CHILDREN\'S UCSD' 
                                                    AND Account_List_Item_Count__c < 1 
                                                    AND OwnerId In: userIdsSet];



 
Yoni LegacyYoni Legacy
Here is the edited code. In the debug log, it's catching all the Account List records with 0 Account list items and the owner id is in active list set..

public class Eisai_AccountListDeletion_cls {
    Set<Id> userIdsSet = new Set<Id>();
    List<User> activeUSerList;
    List<Account_List_vod__c> accListRecsList;
    List<Account_List_vod__c> accListToDelete = new List<Account_List_vod__c>();
   
    //Contructor
    public Eisai_AccountListDeletion_cls(){
       activeUSerList = [SELECT Id,Profile_Name_esi__c
                                FROM User
                                WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                AND IsActive = TRUE ORDER BY Profile_Name_vod__c];
       
            for(User userIds : activeUSerList){
                userIdsSet.add(userIds.Id);
            }
        System.debug('User id: ' + userIdsSet);
        
        getAccListRecords();
        
    }//end of Constructor
   
    //1st block
    public void getAccListRecords(){
       
     accListRecsList = [SELECT Id, Name, Account_List_Item_Count__c
                                                    FROM Account_List_vod__c
                                                    WHERE Account_List_Item_Count__c < 1 
                                                    AND OwnerId In: userIdsSet]; 
                                                    
    System.debug('List of Account List Records to delete ' + accListRecsList);                                               
       
            for(Account_List_vod__c accListRec : accListRecsList){
                        accListToDelete.add(accListRec);                 
            }
    
   try{
       delete accListToDelete;
        System.debug('Deleted number of records '+ accListToDelete.size());
    }catch(DmlException e){
        System.debug(e.getdmlMessage(0));
    }catch(Exception e) {
       System.debug(e.getMessage());
    }

    
    }//end of 1st block
}

 
badibadi
How many records are returning in debug logs for accListRecsList? Do you see any errors in the try and catch block?
Yoni LegacyYoni Legacy
I'm not exactly sure but it's multiple records. I checked some of those records, and the criteria were met. I didn't see any errors in the try and catch block actually which is stranger.
badibadi
I do not see any problem in the code.
If you execute this Eisai_AccountListDeletion_cls eDel= new  Eisai_AccountListDeletion_cls();
and if you can see in the logs debug statement results for line 33 executed, then you should be seeing debug statements results for try/catch block

If possible paste the debug log contents here.
Yoni LegacyYoni Legacy
Badi,

I think there is an existing Trigger which interfere on the class. I tried to turn off the trigger and it's working.Before I deactived the said trigger, when I executed the class, I got this message in the debug logs.
 
12:23:42.55 (3037486857)|FATAL_ERROR|System.DmlException: Delete failed. First exception on row 0 with id a1A12000001z1lEEAQ; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = a1A12000001z1lE) is currently in trigger Eisai_AccountListTrigger, therefore it cannot recursively delete itself: []

Anythoughts about the error?

Thanks
badibadi
I think your trigger is either trying to update the record you just deleted or trying to delete it. 
Hope this link helps
https://help.salesforce.com/apex/HTViewSolution?id=000005278&language=en_US
Yoni LegacyYoni Legacy
Thanks Badi for your help.. I hope you can help me in the future as well.. 
badibadi
Sure. Definetly. I would be happy to
Yoni LegacyYoni Legacy
Hi Badi,

I hope you are free again to help. I am stucked again in one apex class. May concern is in the link below.

http://developer.salesforce.com/forums/ForumsMain?id=906F0000000kDxwIAE

Thank you again in advance.