1

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:

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
}
  • Are you getting an exception of any kind? Have you tried outputting any of the list values to system.debug(...)? – battery.cord Jun 3 '16 at 14:49
  • 1
    You don't make a call to getActiveUserIds method. I don't think your userIdsSet is populated therefore there is nothing to delete. – tugce Jun 3 '16 at 14:58
  • @battery.cord I run it but there is no logs showing and the Account List HO_RADY\'S CHILDREN\'S UCSD isn't deleted. – Mariones Jun 3 '16 at 15:31
  • @TugceSirin: I'm sorry I can understand what is your comment as I'm new in development as I said. If you can give me a sample code. I can check it. – Mariones Jun 3 '16 at 15:34
  • from where you are calling your getAccListRecords method from page ? – Himanshu Jun 3 '16 at 15:38
1

Unless there is a specific reason for a list, I would use a map keyset to build the list of active user Ids. Also, if a list of items is built to be deleted you don't need to query any other fields besides the Id.

Try below in Execute Anonymous in the developer console to verify it's what you are looking for before executing any deletes.

Set<Id> userIdSet = (new Map<Id, User>([
    SELECT  Id
    FROM User
    WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
            OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%')  
        AND IsActive = TRUE
])).keySet();
System.debug(userIdSet);
/* Without casting map you can do it this way as well
Map<Id, User> userMap = new Map<Id, User>([
    SELECT Id, 
    FROM   USER 
    WHERE  ( Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
          OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%' ) 
       AND IsActive = TRUE  
]);
Set<Id> userIdSet = userMap.keySet();
*/

Once you have your set to search for the owner Id compared to the active users. Unless I'm misinterpreting something you should be able to filter by Account_List_Item_Count__c in the same query.

// Return all accounts created by the active users
List<Account_List_vod__c> accListToDelete = [
    SELECT Id
    FROM Account_List_vod__c 
    WHERE Name ='HO_RADY\'S CHILDREN\'S UCSD' 
        AND Account_List_Item_Count__c = 0
        AND OwnerId In: userIdsSet
];
System.debug(accListToDelete);

Also, you should be able to run it one query as well, so try this from the query editor.

SELECT Id 
FROM   Account_List_vod__c 
WHERE  Name = 'HO_RADY\'S CHILDREN\'S UCSD' 
       AND Account_List_Item_Count__c = 0 
       AND OwnerId IN (SELECT Id 
                       FROM   User 
                       WHERE  ( Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                 OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%' ) 
                              AND IsActive = TRUE)

Here's an example Apex Class and Page that will give you an idea how this work using the Account object where I added a rollup summary field on Account called Number_of_Opportunities__c that counts the number of opportunities attached to the account (similar to your count field I'm assuming).

Controller:

public class AccountDelCtrl {

    public AccountDelCtrl() {       
    }

    public List<Account> accounts {
        get {
            return [
                SELECT  Name, 
                        Owner.Name, 
                        Owner.Profile.Name,
                        Number_of_Opportunities__c
                FROM   Account
                WHERE  Name LIKE '%Test%'
                AND Number_of_Opportunities__c = 0
                AND OwnerId IN (SELECT Id 
                                FROM   User 
                                WHERE  ( Profile.Name LIKE '%System Administrator%' 
                                        OR Profile.Name LIKE '%Standard%' ) 
                                AND IsActive = TRUE) 
                LIMIT 10
            ];
        }
        private set;
    }

    public void deleteAccounts() {
        if (accounts != null && accounts.size() > 0) {
            try {
                delete accounts;
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Successfully deleted ' + accounts.size() + ' accounts.'));
            } catch (DmlException e) {
                ApexPages.addMessages(e);
            }
        }
    }
}

Page:

<apex:page controller="AccountDelCtrl">
    <apex:messages />
    <apex:pageMessages  id="pmsg" />
    <apex:form>
        <apex:commandButton action="{!deleteAccounts}" rerender="pmsg, pbAccounts" value="Delete Accounts"/>
        <apex:pageBlock >
            <apex:pageBlockTable value="{!accounts}" var="account" id="pbAccounts">
                <apex:column value="{!account.Name}"/>
                <apex:column >
                    <apex:facet name="header">Owner</apex:facet>
                    <apex:outputText value="{!account.Owner.Name}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">Owner Profile</apex:facet>
                    <apex:outputText value="{!account.Owner.Profile.Name}"/>
                </apex:column>
                <apex:column value="{!account.Number_of_Opportunities__c}"/>
            </apex:pageBlockTable> 
        </apex:pageBlock>
    </apex:form>
</apex:page>
  • Hmm I actually use a set to put in all the active user id then query all Account List records which OwnerId in: userIdsSet. Does it makes any difference if I use map instead? Thanks – Mariones Jun 3 '16 at 16:29
  • @Noiram Basically using a Map and using the keyset saves you from creating a list and then looping through it. Try the above query in the console. It should return what you are looking for because you check the OwnerId compared to the result of the User query. – Andrew L. Jun 3 '16 at 16:38
  • I see, you may use call map since the records inside the map has been filtered already right? I run the query in console, it's giving me a single Id which is the ID of the Account LIst – Mariones Jun 3 '16 at 16:44
  • @Noiram In this case the Map key/value pairs are built directly from Object Account_List_vod__c query (which is the filter). The key is the the Account_List_vod__c Id and the value is the Account_List_vod__c record. The resulting map keyset are all the keys (Ids) in the Map. Here is a good explanation of Salesforce Collections - Maps, Lists, Sets – Andrew L. Jun 3 '16 at 16:50
  • I'm just really new in this. Would you mind asking you what are the missing and incorrect in my code which is not working? – Mariones Jun 3 '16 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.