• Yoni Legacy
  • NEWBIE
  • 30 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 12
    Questions
  • 40
    Replies
Hello experts,

I would like to ask for your assistance on how can I insert merged fields in html custom email template.

I need to create html template for this message:

Dear ${contact},
The engineer working your case is proposing a resolution. Please review the information provided and let us know if you are happy to accept the resolution or if you have any further updates regarding this specific case.
Review your full case detail on the Support Portal to accept or comment further: LINK
Please be aware that if no response is received within 7 days, this case will be automatically closed and any further query will need to be managed through a new support case submission.

(INSERT ALSO THE SCRIPT BELOW AS ACCEPT AND REJECT BUTTON)
(function runMailScript(current, template, email, email_action, event) { template.print('<a href="mailto:support@snowsoftware.com?subject=Re%3A' + current.number + '%20-%20SOLUTION ACCEPTED&body=%0A' + email.watermark + '">Accept solution</a><br><br>'); template.print('<a href="mailto:support@snowsoftware.com?subject=Re%3A' + current.number + '%20-%20SOLUTION REJECTED&body=Solution rejected%0AWrite comments here:%0A%0A%0A%0A%0A%0A' + email.watermark + '">Reject solution</a><br><br>'); })(current, template, email, email_action, event);

You may also receive a customer satisfaction survey; if you do, please take the time to complete as we value your feedback. This enables us to continue to provide quality support services.
Kind regards,
Snow Software Support Services

Thank you In advanced!
Hello,

I'm very new to apex coding. I was informed that the proper way of creating trigger is to create a trigger then call apex class methods. Is that right?

I tried it on my end with a very simple trigger but I can't make it work.
Basically, what I want is that when I create Account, it will automatically create a Contact under the Account with Account is equal to Account id and contact last name is equal to account last name.

Attached is my trigger and class.

apex trigger 

Class
User-added image

Thank you
Marion

I hope you can help me again experts.
My question is, can I still update locked records (No edit button after submitting the record) the page is visualforce, I'm not sure if the edit button is just hidden after the status changed to submitted or the record is totally locked.

Here is the code which I created and somehow is not editing the Call date/time of the child records.
 
global class Eisai_Batch_updateAttendeeCallDate_cls implements Database.batchable<sObject>, Database.Stateful{
Map<Id, Call2_vod__c> Parentid_Map = new Map<Id, Call2_vod__c>();
List<Call2_vod__c> toUpdateChildCalls_List = new List<Call2_vod__c>();
Set<Id> updatedCallsId_Set = new Set<Id>();
Set<Id> failedToUpdateId_Set = new Set<Id>();

global Iterable<sObject> start(Database.BatchableContext info) {
    return Database.getQueryLocator([SELECT Id, Call_Datetime_vod__c FROM Call2_vod__c WHERE Is_Parent_Call_vod__c = 1 AND Status_vod__c = 'Submitted_vod']);
} //end of start part

global void execute(Database.BatchableContext info, List<Call2_vod__c> scope){


    for(Call2_vod__c newC: scope){
        Parentid_Map.put(newC.Id, newC);
    }

    System.debug('<----MAP RECORD COUNT---->' + Parentid_Map.size());

    List<Call2_vod__c> childCalls = [SELECT Id, Call_Datetime_vod__c, Parent_Call_vod__c FROM Call2_vod__c 
                                        WHERE Parent_Call_vod__c IN: Parentid_Map.keySet()];


    for(Call2_vod__c child : childCalls){

        Call2_vod__c pCallRec = Parentid_Map.get(child.Parent_Call_vod__c);

        if(pCallRec != Null && pCallRec.Id == child.Parent_Call_vod__c){
                child.Call_Datetime_vod__c = pCallRec.Call_Datetime_vod__c;
                toUpdateChildCalls_List.add(child);
         }                               
    }


    System.debug('<-----CHILD RECORD TO UPDATE----->: ' +   toUpdateChildCalls_List.size());

    for(Database.SaveResult sr : Database.update(toUpdateChildCalls_List,false)
    {
        if(sr.isSuccess()){
            updatedCallsId_Set = sr.getId();    
        }else {
            failedToUpdateId_Set = sr.getId();
        }
    }
}//end of execute part

global void finish(Database.BatchableContext info){
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setTargetObjectId(UserInfo.getUserId());
    mail.setSaveAsActivity(false);
    mail.setSenderDisplayName('Salesforce Support');
    mail.setSubject('Eisai_Batch_updateAttendeeCallDate_cls Batch Job Run Completed');

    mail.setPlainText(
        'Child calls Call Date/Time field are now aligned with the Call Date/Time field of their Parent Call' + '\n' +
        'Thanks!');
    Messaging.sendEmail(new Messaging.Email[] { mail });
}//end of finish part
}//end of batch

I'm just a self taught trying hard developer and lone developer in the team. So please help. Thanks in advance
Hi Experts,

I am really new in apex class. I hope you can help me, I created a batch job to create/insert Account List records.
Link to my batch job question: http://salesforce.stackexchange.com/questions/132504/help-in-converting-my-apex-class-to-batch-job?noredirect=1#comment188702_132504

This Account List has Account List Item (RELATIONSHIP: Master-Detail)
Here is the code of my Account List Item
 
public with sharing class Eisai_InsertAccountListItem_cls{
    List<Account_List_Item_vod__c> toInsertAcctListItem = new List<Account_List_Item_vod__c>();
    List<Account_List_vod__c> allHOAccountList = new List<Account_List_vod__c>();
    List<Affiliation_vod__c> allAffiliationList = new List<Affiliation_vod__c>();
    List<Affiliation_vod__c> allChildAffList = new List<Affiliation_vod__c>();
    List<User> usersIdList; 
    Set<Id> usersIdSet = new Set<Id>();
    Set<String> affToAcctValSet = new Set<String>();
    Set<String> allHOAccountListName = new Set<String>();

    public Eisai_InsertAccountListItem_cls(){


        for (Affiliation_vod__c allAffiliationList : [SELECT ID, OwnerId, Name, From_Account_vod__c, To_Account_Value__c FROM Affiliation_vod__c 
                                                                                WHERE Parent_vod__c = false
                                                                                AND OwnerId IN:getActiveUsers()])
        {
            if(!affToAcctValSet.contains(allAffiliationList.To_Account_Value__c)){
                  allChildAffList.add(allAffiliationList);
                affToAcctValSet.add(allAffiliationList.To_Account_Value__c);
            }
        }

        for (Account_List_vod__c allHOAccountListQuery : [SELECT Id, OwnerId, Name, Name_Substring__c FROM Account_List_vod__c 
                                                                                                      WHERE Name_Substring__c IN :affToAcctValSet]){
            allHOAccountList.add(allHOAccountListQuery);
        }

            for(Affiliation_vod__c affRec: allChildAffList)
                for(Account_List_vod__c allHOAccountListInsert : allHOAccountList){
                    if(allHOAccountListInsert.Name_Substring__c.equals(affRec.To_Account_Value__c)){ 
                  //     &&  allAffiliationList.OwnerId.equals(allHOAccountListInsert.OwnerId)){
                        Account_List_Item_vod__c AccListItem = new Account_List_Item_vod__c(
                              Account_List_vod__c = allHOAccountListInsert.Id,
                              Account_vod__c = affRec.From_Account_vod__c
                        );
                        toInsertAcctListItem.add(AccListItem);
                     }
                }

    Database.SaveResult[] srList = Database.insert(toInsertAcctListItem, false);

    for (Database.SaveResult sr: srList){
        if(sr.isSuccess()){
            System.debug('Inserted Account List Item Id: ' + sr.getId());
        } else {
            for(Database.Error err : sr.getErrors()){
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
        }
               }
    }


}//end of Constructor

    public Set<Id> getActiveUsers(){

        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%'
                                             OR Profile_Name_vod__c LIKE '%Eisai_System%') 
                                      AND IsActive = TRUE]); 

        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
}//end of Class

I am receiving an error message like this below:

User-added image

Note: There are many child affiliation record (Parent = False) with 1 To_Account_vod_value(Account Name) and but different From_Account_vod (Person Accounts) So I tried to limit to get only 1 record (To_Account_vod_value) by this line of codes:
 
for (Affiliation_vod__c allAffiliationList : [SELECT ID, OwnerId, Name, From_Account_vod__c, To_Account_Value__c FROM Affiliation_vod__c 
                                                                        WHERE Parent_vod__c = false
                                                                        AND OwnerId IN:getActiveUsers()])
{
    if(!affToAcctValSet.contains(allAffiliationList.To_Account_Value__c)){
          allChildAffList.add(allAffiliationList);
        affToAcctValSet.add(allAffiliationList.To_Account_Value__c);
    }
}

Thanks 
Marion
Hi Experts,

I hope someone can help to convert my class to batch job. This is the first time that I will create a batch job and only a newbie in apex coding.

Here is my class which is working but hitting the DML limit as there are more than 10k to insert.
 
public with sharing class Eisai_AccountListCreation_New {
    
    List<Account_Territory_Mapping__c> allAtmRecs = new List<Account_Territory_Mapping__c>();
    List<Account_List_vod__c> ToInsertAcctList = new List<Account_List_vod__c>();
        
    public Eisai_AccountListCreation_New(){
        
        allAtmRecs = [Select Account_Name_String__c, Account_Owner__c FROM Account_Territory_Mapping__c 
                      												  WHERE Owner_Territory__c LIKE 'EP%' 
                     												  OR Owner_Territory__c LIKE 'QM%'];
        
        for(Account_Territory_Mapping__c  Atm : allAtmRecs){
            if(Atm.Account_Name_String__c != Null && Atm.Account_Owner__c !=Null){
                    Account_List_vod__c AccList = new Account_List_vod__c();
                        AccList.Name = 'HO_' + Atm.Account_Name_String__c;
                        AccList.OwnerId = Atm.Account_Owner__c;
                        ToInsertAcctList.add(AccList);
            }   
        }
        
      System.debug('No of Account List to insert: ' + ToInsertAcctList.size());
        
      Database.insert(ToInsertAcctList,false);

      /*  
      for (Database.SaveResult sr: srList){
            if(sr.isSuccess()){
                System.debug('Inserted Account List count: ' + sr.getId());
            } else {
                for(Database.Error err : sr.getErrors()){
                System.debug(err.getStatusCode() + ': ' + err.getMessage());
                }
            }
       } */
        
    }//End of Constructor

}//End of Class

Below is the batch class which I tried to create but I encountered an error.
 
global class Eisai_BatchInsertAcctList implements Database.batchable<sObject>, Database.Stateful { 
    
    global string query = 'Select Account_Name_String__c, Account_Owner__c FROM Account_Territory_Mapping__c
        															  	   WHERE Account_Name_String__c != Null 
                     												       AND Account_Owner__c !=Null;
                      												  
	global Iterable<sObject> start(Database.BatchableContext info){
        return Database.getQueryLocator(query);
    }
    
	global void execute(Database.BatchableContext info, List<Account_Territory_Mapping__c> scope){
        List<Account_List_vod__c> ToInsertAcctList = new List<Account_List_vod__c>();
        
        for(Account_Territory_Mapping__c  Atm : scope){
            if(Atm.Account_Name_String__c != Null && Atm.Account_Owner__c !=Null){
                    Account_List_vod__c AccList = new Account_List_vod__c();
                        AccList.Name = 'HO_' + Atm.Account_Name_String__c;
                        AccList.OwnerId = Atm.Account_Owner__c;
                        ToInsertAcctList.add(AccList);
            }   
        }
        
    Database.insert(ToInsertAcctList,false);
        
	}
	global void finish(Database.BatchableContext info){
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'marion.c.d.legacion@accenture.com'};
        mail.setToAddresses(toAddresses);
        mail.setSenderDisplayName('Salesforce Support');
        mail.setSubject('Eisai_BatchInsertAcctList Batch Job Run Complete');
            
         System.debug('Insert Account List Count: ' + ToInsertAcctList.size());
           
    }
        
}//end of batch class

Below is the error messasge which I encountered:
User-added image

Thanks,
Marion
public with sharing class Eisai_InsertAcctList_cls {
    
    List<User> usersIdList; 
    Set<Id> usersIdSet = new Set<Id>(); 
    Set<Id> AffFromAcctSet = new Set<Id>(); 
    Set<String> uniqueFieldSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs;
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
	
	//added Collections
	List<Id> fromAcctIdList = new List<Id>();
	List<TSF_vod__c> terr = new List<TSF_vod__c>();
	List<UserTerritory> userTerrInGroupAcct = new List<UserTerritory>();
	Set<String> terrSet = new Set<String>(); 
	Set<Id> terrIdSet = new Set<Id>();
	
    
    public Eisai_InsertAcctList_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE Parent_vod__c = True 
                                                         AND From_Account_RecType__c = 'Group_Practice_Account']);
                                                    //   AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Count '+ allAffParentRecs.size());
		
		//added SOQL Queries
		for(Affiliation_vod__c affFromAcct : allAffParentRecs){
				fromAcctIdList.add(affFromAcct.From_Account_vod__c);
		}
        
		for(TSF_vod__c terr : [SELECT Id, Territory_vod__c, Account_vod__c FROM TSF_vod__c WHERE Account_vod__c IN:fromAcctIdList]){
				terrSet.add(terr.Territory_vod__c);
		}
		
		System.debug('Territory count: ' + terrSet.size());
		
		for(Territory terrId : [SELECT Id, Name FROM Territory WHERE Name IN:terrSet]){
				terrIdSet.add(terrId.Id);
		}
		
		userTerrInGroupAcct = [SELECT TerritoryId, UserId FROM UserTerritory WHERE TerritoryId IN: terrIdSet];
        
        System.debug('No. of user owns the Group Practice Account: ' + userTerrInGroupAcct.size());
        
        //end of added SOQL Queries
		
		
        for(Account_List_vod__c xAcctListRecs  : [Select Name_Populate_Unique_Owner__c FROM Account_List_vod__c 
                                                  									   WHERE Name_Populate_Unique_Owner__c != Null])
                                                  									//   WHERE OwnerId IN: getActiveUsers()])
        {
            uniqueFieldSet.add(xAcctListRecs.Name_Populate_Unique_Owner__c);
        }
        
        for(Affiliation_vod__c allParentAffRecs: allAffParentRecs){
            for(UserTerritory userTerrId : userTerrInGroupAcct){
                if(!AffFromAcctSet.contains(allParentAffRecs.From_Account_vod__c)){
                    Account_List_vod__c AccListRec = new Account_List_vod__c();    
                        AccListRec.Name = 'HO_' + allParentAffRecs.From_Account_Value__c; 
                        AccListRec.Icon_Name_vod__c = '0';  
                        AccListRec.OwnerId = userTerrId.UserId;
                        AffFromAcctSet.add(allParentAffRecs.From_Account_vod__c);
                        newAccListRecList.add(AccListRec);
             	}
        	}
        }
        
        for(Account_List_vod__c accList : newAccListRecList){
            if(!uniqueFieldSet.contains(accList.Name + accList.OwnerId)){
                InsertedAccList.add(accList);
            }
        }
        
        Database.SaveResult[] srList = Database.insert(InsertedAccList, false);

        for (Database.SaveResult sr: srList){
            if(sr.isSuccess()){
                System.debug('Inserted Account List count: ' + sr.getId());
            } else {
                for(Database.Error err : sr.getErrors()){
                System.debug(err.getStatusCode() + ': ' + err.getMessage());
                }
            }
        }
    }//end of 1st block
   
   /*         
   public Set<Id> getActiveUsers(){
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    } */
    
}// End of Class
How can I make the Owner of Account List to be the UserId returned in userTerrInGroupAcct (Set)

Here is the query:
userTerrInGroupAcct = [SELECT TerritoryId, UserId FROM UserTerritory WHERE TerritoryId IN: terrIdSet];

If there are 12 users returned on the query above, there should be 12 Account List created, the OwnerId should be each of the 12 users.

Thanks. 
 
Hi Experts,

I created a class to insert Account List Item Record for every Affiliation child record. 

Here is the code, and it's working in a single record, but when I executed the code manual in developer console I got an error message: 
Error message

Here is my code below: I think I need to use map but I'm just new and still confused on using map.
 
public with sharing class Eisai_InsertAccListItem_cls {
    
    List<Affiliation_vod__c> affChildRecsList;
    List<Account_List_vod__c> acctListInDb;
    List<Account_List_Item_vod__c> newAccListItem = new List<Account_List_Item_vod__c>();
    Set<Id>usersIdSet = new Set<Id>();
    
    public Eisai_InsertAccListItem_cls(){
        
        affChildRecsList = new List<Affiliation_vod__c>([SELECT Id, From_Account_vod__c, To_Account_Value__c, OwnerId
                                                         FROM Affiliation_vod__c 
                                                         WHERE Parent_vod__c = False
                                                         AND OwnerId IN :ActiveUsers()]);
        
            System.debug('Child Affiliation Records count ' + affChildRecsList.size()); 
        
        
        acctListInDb = new List<Account_List_vod__c>([Select Id, Name, OwnerId FROM Account_List_vod__c 
                                                      WHERE OwnerId IN :ActiveUsers()]);
        
            System.debug('Account List Records count ' + acctListInDb.size());
        
        
        
        for(Affiliation_vod__c affChild : affChildRecsList){
            for(Account_List_vod__c acctList : acctListInDb){
               if((acctList.Name.substring(3) == affChild.To_Account_Value__c)
                  && (affChild.OwnerId == acctList.OwnerId)){
                       Account_List_Item_vod__c AccListItem = new Account_List_Item_vod__c();
                       AccListItem.Account_List_vod__c = acctList.Id;
                       AccListItem.Account_vod__c = affChild.From_Account_vod__c;
                       newAccListItem.add(AccListItem);
                 }
             }
         }
   
        
        try{        
            insert newAccListItem ;
            System.debug('New Account List Item Records: ' + newAccListItem);
        }catch(DMLException e){
            System.debug('exeption catch ' + e.getMessage()); 
        }
        
        
    }//End of Constructor   
    
    public Set<Id> ActiveUsers(){
        
       List<User> usersIdList;
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                      OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
    
} //End of Class

Thanks for the help in advance
Hi experts,

I created a class to insert Account List record. The condition is allow duplicate Account List name, but the owner is different from the existing record. 

Example:

Exisiting record:
Account List Name: HO_Test
Owner: Marion Legacion

To be inserted record:
1. Account List Name: HO_Test
   Owner: Marion Legacion
Result: This record cannot be inserted since there is a duplicate both Account List Name and Owner.

2. Account List Name: HO_Test
Owner: Noiram Legacion
Result: A record will be created since Marion Legacion is different from Noiram Legacion.

Note: I created a Unique field to be updated by Workflow to populate the Account List Name and Owner (Formula: Account List Name & OwnerId)


Here is my code which is not working.
 
public with sharing class InsertAccountListRec_TEST_cls {
    
    List<User> usersIdList; 
	Set<Id> usersIdSet = new Set<Id>(); 
	Set<Id> AffFromAcctSet = new Set<Id>(); 
	Set<String> uniqueFieldSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs = new List<Affiliation_vod__c>();
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
    
    public InsertAccountListRec_TEST_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE (From_Account_vod__r.Id = '0011200001GNrb0AAD' AND Parent_vod__c = True) 
														 AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Count '+ allAffParentRecs.size());
		
        for(Account_List_vod__c xAcctListRecs  : [Select OwnerId, Unique_Owner_Name__c FROM Account_List_vod__c 
                                                  WHERE Name = 'HO_RADY\'S CHILDREN\'S UCSD'
                                                  AND OwnerId IN: getActiveUsers()])
        {
            uniqueFieldSet.add(xAcctListRecs.Unique_Owner_Name__c);
        }
        
        for(Affiliation_vod__c allParentAffRecs: allAffParentRecs){
            if(!AffFromAcctSet.contains(allParentAffRecs.From_Account_vod__c)){
                Account_List_vod__c AccListRec = new Account_List_vod__c();    
                AccListRec.Name = 'HO_' + allParentAffRecs.From_Account_Value__c; 
                AccListRec.Icon_Name_vod__c = '0';	
                AccListRec.OwnerId = allParentAffRecs.OwnerId;
                AffFromAcctSet.add(allParentAffRecs.From_Account_vod__c);
                newAccListRecList.add(AccListRec);
            } 
        }
        for(Account_List_vod__c accList : newAccListRecList){
            if(!uniqueFieldSet.contains(accList.Name + accList.OwnerId)){
                InsertedAccList.add(accList);
            }
        }
        
        try{        
            insert InsertedAccList ;
            System.debug('New Account List Records: ' + InsertedAccList);
        }catch(DMLException e){
            System.debug('exeption catch ' + e.getMessage()); 
        }
    }//end of 1st block
    
    public Set<Id> getActiveUsers(){
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
}// End of Class

Unique_Owner_Name__c - is the unique field.

I queried all the Unique_Owner_Name__c field of all Account List record and I checked the unique field set to see if the (accList.Name + accList.OwnerId) is existing, if not then add the Account List record to a list and DML Insert

Please help

Thanks
Marion
 
Hi, 

Can somebody help me with the logic on the following: 

Account List name is existing, but the ownerid is not existing (Different user)  -> insert ok
Account List name is not existing, but owner id is existing in db - insert ok 

Account List name is existing, owner id is existing (Avoid duplicate record with the same Account List name with the same owner)  -> No insert

Basically, I just want to prevent the record to be inserted if the account list name is duplicate and also the same owner, but if the account list has a match in the database, but it's owner is different, it's should be inserted.


Here is my current code: 
 
public with sharing class InsertAccountListRec_TEST_cls {
    
    List<User> usersIdList;
    Set<Id> usersIdSet = new Set<Id>();
    Set<Id> AffFromAcctSet = new Set<Id>();
    Set<Id> xAcctListOidSet = new Set<Id>();
    Set<String> xAcctListNameSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs = new List<Affiliation_vod__c>();
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
    
    
    
    //Creation a list of all Parent Affiliation Records, then add to allParentRecsSet (SET).
    //Start of 1st Block
    public InsertAccountListRec_TEST_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE (From_Account_vod__r.Id = '0011200001GNrb0AAD' 
                                                         AND Parent_vod__c = True)
                                                         AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Count '+ allAffParentRecs.size());
        
        
        for(Account_List_vod__c xAcctListRecs  : [Select OwnerId, Name FROM Account_List_vod__c 
                                                  WHERE Name LIKE 'HO_%'
                                                  AND OwnerId IN: getActiveUsers()]){
                                                                      xAcctListOidSet.add(xAcctListRecs.OwnerId);
                                                      				  xAcctListNameSet.add(xAcctListRecs.Name);
                                                                  }
        
        System.debug('Account List Record Count '+ xAcctListRecs);
        
        for(Affiliation_vod__c allParentAffRecs: allAffParentRecs){
            if(!AffFromAcctSet.contains(allParentAffRecs.From_Account_vod__c)){
                Account_List_vod__c AccListRec = new Account_List_vod__c();    
                AccListRec.Name = 'HO_' + allParentAffRecs.From_Account_Value__c; 
                AccListRec.Icon_Name_vod__c = '0';	
                AccListRec.OwnerId = allParentAffRecs.OwnerId;
                AffFromAcctSet.add(allParentAffRecs.From_Account_vod__c);
                newAccListRecList.add(AccListRec); 
            }
        }
               
         for(Account_List_vod__c acctListToCreate : newAccListRecList){
             if(xAcctListNameSet.contains(acctListToCreate.Name) && !xAcctListOidSet.contains(acctListToCreate.OwnerId)){
                       InsertedAccList.add(acctListToCreate);
             }     
         }	
               
               insert InsertedAccList ;
               System.debug('New Account List Records: ' + InsertedAccList);
	}//end of 1st block
    
    
    public Set<Id> getActiveUsers(){
    
            usersIdList = new List<User>([SELECT Id
                                     FROM User
                                     WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                     OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                     AND IsActive = TRUE]); 
        
            for(User users : usersIdList){
                    usersIdSet.add(users.Id);  
            }
        return usersIdSet;
    }
}// End of Class
The logic which is not working is in line 47 to 51

Thanks for the help..
 
Hi, 

Can somedoby help me to make my code work? I am really new in development and none is mentoring me. I tried my best to make the code below work but it's not working.. It's not creating Account List.

Here is my code.
 
public with sharing class InsertAccountListRec_TEST_cls {
	
	Set<Id> allParentRecsSet = new Set<Id>();
    Set<Account_List_vod__c> accRecSet = new Set<Account_List_vod__c>();
Set<Account_List_Item_vod__c>();
    List<Affiliation_vod__c> allAffParentRecs = new List<Affiliation_vod__c>();
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
List<Account_List_Item_vod__c>();
    Map<Id,Id> mapAffRecs = new Map<Id, Id>();
    Map<Id, String> acctListMap = new Map<Id,String>();
	Map<String,Id> mapAffOwner = new Map<String,Id>();
    
    //Creation a list of all Parent Affiliation Records, then add to allParentRecsSet (SET).
    //Start of 1st Block
    public List<Affiliation_vod__c> getParentAffRecs(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, From_Account_vod__c, To_Account_vod__c,Business_Account__c 
                                                         FROM Affiliation_vod__c
                                                         WHERE (From_Account_vod__r.Id = '0011200001GNrb0AAD' 
														 AND Parent_vod__c = True)
														 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)]);
																						
		System.debug('Parent Affiliation record count '+ allAffParentRecs.size());																					
        
        //Iterate on the Affiliation records (Group Practice Accounts) 
        //If the From_Account_vod__c field has a value (meaning: Not blank), add the value to allParentRecsSet (SET)
       allParentRecsSet = new Set<Id>();
        for(Affiliation_vod__c aParentRecs: allAffParentRecs){
            if(aParentRecs.From_Account_vod__c != Null){
                allParentRecsSet.add(aParentRecs.From_Account_vod__c);
            }
			
			if(!allParentRecsSet.contains(aParentRecs.From_Account_vod__c)){
                mapAffRecs.put(aParentRecs.Id, aParentRecs.From_Account_vod__c); 
				mapAffOwner.put(String.ValueOf(aParentRecs.Name),aParentRecs.OwnerId);
            }
        }
        return allAffParentRecs;
    }//end of 1st block
    
   	
	//Start of 2nd block
    //For every Parent Affiliation record inside the affParentRecsLst, check if the accRecSet (Set) doesn't contains Account List records,
    // -->If true, add the Account List Record to accRecSet (SET) and put into acctListMap (MAP).
	//Pass the Account List records from accRecSet (SET) to newAccListRecList (LIST).After that,Insert the records inside the newAccListRecList (LIST)
    public Map<Id, String> createAcctListRecs(){
        acctListMap = new Map<Id,String>();
        accRecSet = new Set<Account_List_vod__c>();
        
        for(Affiliation_vod__c allParentAffRecs : allAffParentRecs){
            Account_List_vod__c newAccListRec = new Account_List_vod__c();    
            newAccListRec.Name = 'HO_' + mapAffRecs.get(allParentAffRecs.Id); 
            newAccListRec.Icon_Name_vod__c = '0';	
			newAccListRec.OwnerId = mapAffOwner.get(allParentAffRecs.Name);
																			  
            if(!accRecSet.contains(newAccListRec)){							  
                accRecSet.add(newAccListRec);
                acctListMap.put(newAccListRec.Id, newAccListRec.Name);
           
            } 
            
            for(Account_List_vod__c acctListRecs : accRecSet){
                newAccListRecList.add(acctListRecs);
                System.debug('Account List records to be created ' + newAccListRecList);
            }
            insert newAccListRecList;     
        }
        return acctListMap;
    }//end of n2d block	

}

Thanks in advance to your help.
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
Hi,

I am a beginner in apex coding and honestly don't know if my code will work as expected.

I tried my best to accomplish atleast the insert method for Account List. Below is the code.

public with sharing class createAndMaintainAccountList_cls{
    Set<Id> allParentRecsSet = new Set<Id>();
    Set<Account_List_vod__c> setAccRec = new Set<Account_List_vod__c>();
    Set<Account_List_Item_vod__c> accListItemSet = new Set<Account_List_Item_vod__c>();
    List<Affiliation_vod__c> allAffParentRecs = new List<Affiliation_vod__c>();
    List<Affiliation_vod__c> affParentRecsLst = new List<Affiliation_vod__c>();
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Affiliation_vod__c> affChildRecsList = new List<Affiliation_vod__c>();
    List<Account_List_Item_vod__c> accListItemList = new List<Account_List_Item_vod__c>();
    Map<Id,Id> mapAffRecs = new Map<Id, Id>();
    Map<Id, String> acctListMap = new Map<Id,String>();
    Map<Id,Id> affChildRecsMap = new Map<Id,Id>();
    
    //Creation a list of all Parent Affiliation Records, then add to parentAffRecsLst List.
    //Start of 1st Block
    public Set<Id> getParentAffRecs(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, From_Account_vod__c, To_Account_vod__c,Business_Account__c 
                                                         FROM Affiliation_vod__c
                                                         WHERE Business_Account__c = 'Group_Practice_Account' AND Parent_vod__c = True]);
        
        //Iterate on the Affiliation records (Professional) 
        //If the From_Account_vod__c field has a value (meaning: Not blank), add the value to allParentRecsSet (Set)
        allParentRecsSet = new Set<Id>();
        for(Affiliation_vod__c aParentRecs: allAffParentRecs){
            if(aParentRecs.From_Account_vod__c != Null){
                allParentRecsSet.add(aParentRecs.From_Account_vod__c);
            }
        }
        return allParentRecsSet;
    }//end of 1st block
    
    //Start of 2nd block
    //List of Affliation records (Group Account) which Business_Account__c is equal to Group Practice 
    //and From_Account_vod__c record is in allParentRecsSet
    public Map<Id,Id> putAffParentIdAndFromAcct(){
        affParentRecsLst = new List<Affiliation_vod__c>([SELECT Id, From_Account_vod__c, To_Account_vod__c,Business_Account__c 
                                                         FROM Affiliation_vod__c 
                                                         WHERE Business_Account__c = 'Group_Practice_Account' 
                                                         AND From_Account_vod__c in:allParentRecsSet]);
        
        //Creation of map (Key: Affiliation Id, Values: From_Account_vod__c)
        mapAffRecs = new Map<Id, Id>();
        for(Affiliation_vod__c affParentRecs : affParentRecsLst){
            if(!allParentRecsSet.contains(affParentRecs.From_Account_vod__c)){
                mapAffRecs.put(affParentRecs.Id, affParentRecs.From_Account_vod__c);
            }
        }
        return mapAffRecs;
    }//end of 2nd block
    
    
    //Start of 3rd block
    //For every Parent Affiliation record, check if the setAccRec (Set) doesn't contains Account list,
    // if true, create an Account List.
    public Map<Id, String> createAcctListRecs(){
        acctListMap = new Map<Id,String>();
        setAccRec = new Set<Account_List_vod__c>();
        
        for(Affiliation_vod__c allParentAffRecs : affParentRecsLst){
            Account_List_vod__c newAccListRec = new Account_List_vod__c();
            newAccListRec.Name = 'HO_' + mapAffRecs.get(allParentAffRecs.Id);
            newAccListRec.Icon_Name_vod__c = '0';
            
            if(!setAccRec.contains(newAccListRec)){
                setAccRec.add(newAccListRec);
                acctListMap.put(newAccListRec.Id, newAccListRec.Name);
            }else{
                System.debug('-----The Account List already exist-----');
            } 
            
            for(Account_List_vod__c acctListRecs : setAccRec){
                newAccListRecList.add(acctListRecs);
            }
            insert newAccListRecList;     
        }
        return acctListMap;
    }//end of 3rd block
    
    //Start of 4th block
    //List of Affliation records (Professional) which To Account is in allParentRecsSet
    public Map<Id,Id> getChildAffRecs(){
        affChildRecsMap = new Map<Id,Id>();
        
        affChildRecsList = new List<Affiliation_vod__c>([SELECT Id, From_Account_vod__c, To_Account_vod__c,Business_Account__c 
                                                         FROM Affiliation_vod__c 
                                                         WHERE Business_Account__c = 'Professional_vod' 
                                                         AND Parent_vod__c = False
                                                         AND To_Account_vod__c IN :allParentRecsSet]);
        
        
        //In every Affiliation Professional, add Child Affiliation Record Id, From Account vod to affChildRecsMap
        for(Affiliation_vod__c affChildRecs : affChildRecsList){
            affChildRecsMap.put(affChildRecs.Id, affChildRecs.From_Account_vod__c);
        }
        return affChildRecsMap;
    }//end of 4th block 
    
    //Start of 5th Block
    public void createAcctListItemRecs(){
        accListItemSet = new Set<Account_List_Item_vod__c>();
        
            for(Affiliation_vod__c affChildRecsFinal : affChildRecsList){
                Account_List_Item_vod__c newAccListItem = new Account_List_Item_vod__c();
                newAccListItem.Account_List_vod__c = acctListMap.get(affChildRecsFinal.Id);
                newAccListItem.Account_vod__c = affChildRecsMap.get(affChildRecsFinal.Id);
                
                if(!accListItemSet.contains(newAccListItem)){
                    accListItemSet.add(newAccListItem);
                }else{
                    System.debug('-----The Account List Item already exist-----');
                }
            }
            
            for(Account_List_Item_vod__c accListItemRecs: accListItemSet){
                accListItemList.add(accListItemRecs);
            }
            insert accListItemList; 
    }//end of 5th block
}

Note: I guess my question is how to make the above code to execute only for specific profile.

Thanks
Marion
Hello,

I'm very new to apex coding. I was informed that the proper way of creating trigger is to create a trigger then call apex class methods. Is that right?

I tried it on my end with a very simple trigger but I can't make it work.
Basically, what I want is that when I create Account, it will automatically create a Contact under the Account with Account is equal to Account id and contact last name is equal to account last name.

Attached is my trigger and class.

apex trigger 

Class
User-added image

Thank you
Marion

I hope you can help me again experts.
My question is, can I still update locked records (No edit button after submitting the record) the page is visualforce, I'm not sure if the edit button is just hidden after the status changed to submitted or the record is totally locked.

Here is the code which I created and somehow is not editing the Call date/time of the child records.
 
global class Eisai_Batch_updateAttendeeCallDate_cls implements Database.batchable<sObject>, Database.Stateful{
Map<Id, Call2_vod__c> Parentid_Map = new Map<Id, Call2_vod__c>();
List<Call2_vod__c> toUpdateChildCalls_List = new List<Call2_vod__c>();
Set<Id> updatedCallsId_Set = new Set<Id>();
Set<Id> failedToUpdateId_Set = new Set<Id>();

global Iterable<sObject> start(Database.BatchableContext info) {
    return Database.getQueryLocator([SELECT Id, Call_Datetime_vod__c FROM Call2_vod__c WHERE Is_Parent_Call_vod__c = 1 AND Status_vod__c = 'Submitted_vod']);
} //end of start part

global void execute(Database.BatchableContext info, List<Call2_vod__c> scope){


    for(Call2_vod__c newC: scope){
        Parentid_Map.put(newC.Id, newC);
    }

    System.debug('<----MAP RECORD COUNT---->' + Parentid_Map.size());

    List<Call2_vod__c> childCalls = [SELECT Id, Call_Datetime_vod__c, Parent_Call_vod__c FROM Call2_vod__c 
                                        WHERE Parent_Call_vod__c IN: Parentid_Map.keySet()];


    for(Call2_vod__c child : childCalls){

        Call2_vod__c pCallRec = Parentid_Map.get(child.Parent_Call_vod__c);

        if(pCallRec != Null && pCallRec.Id == child.Parent_Call_vod__c){
                child.Call_Datetime_vod__c = pCallRec.Call_Datetime_vod__c;
                toUpdateChildCalls_List.add(child);
         }                               
    }


    System.debug('<-----CHILD RECORD TO UPDATE----->: ' +   toUpdateChildCalls_List.size());

    for(Database.SaveResult sr : Database.update(toUpdateChildCalls_List,false)
    {
        if(sr.isSuccess()){
            updatedCallsId_Set = sr.getId();    
        }else {
            failedToUpdateId_Set = sr.getId();
        }
    }
}//end of execute part

global void finish(Database.BatchableContext info){
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setTargetObjectId(UserInfo.getUserId());
    mail.setSaveAsActivity(false);
    mail.setSenderDisplayName('Salesforce Support');
    mail.setSubject('Eisai_Batch_updateAttendeeCallDate_cls Batch Job Run Completed');

    mail.setPlainText(
        'Child calls Call Date/Time field are now aligned with the Call Date/Time field of their Parent Call' + '\n' +
        'Thanks!');
    Messaging.sendEmail(new Messaging.Email[] { mail });
}//end of finish part
}//end of batch

I'm just a self taught trying hard developer and lone developer in the team. So please help. Thanks in advance
Hi Experts,

I am really new in apex class. I hope you can help me, I created a batch job to create/insert Account List records.
Link to my batch job question: http://salesforce.stackexchange.com/questions/132504/help-in-converting-my-apex-class-to-batch-job?noredirect=1#comment188702_132504

This Account List has Account List Item (RELATIONSHIP: Master-Detail)
Here is the code of my Account List Item
 
public with sharing class Eisai_InsertAccountListItem_cls{
    List<Account_List_Item_vod__c> toInsertAcctListItem = new List<Account_List_Item_vod__c>();
    List<Account_List_vod__c> allHOAccountList = new List<Account_List_vod__c>();
    List<Affiliation_vod__c> allAffiliationList = new List<Affiliation_vod__c>();
    List<Affiliation_vod__c> allChildAffList = new List<Affiliation_vod__c>();
    List<User> usersIdList; 
    Set<Id> usersIdSet = new Set<Id>();
    Set<String> affToAcctValSet = new Set<String>();
    Set<String> allHOAccountListName = new Set<String>();

    public Eisai_InsertAccountListItem_cls(){


        for (Affiliation_vod__c allAffiliationList : [SELECT ID, OwnerId, Name, From_Account_vod__c, To_Account_Value__c FROM Affiliation_vod__c 
                                                                                WHERE Parent_vod__c = false
                                                                                AND OwnerId IN:getActiveUsers()])
        {
            if(!affToAcctValSet.contains(allAffiliationList.To_Account_Value__c)){
                  allChildAffList.add(allAffiliationList);
                affToAcctValSet.add(allAffiliationList.To_Account_Value__c);
            }
        }

        for (Account_List_vod__c allHOAccountListQuery : [SELECT Id, OwnerId, Name, Name_Substring__c FROM Account_List_vod__c 
                                                                                                      WHERE Name_Substring__c IN :affToAcctValSet]){
            allHOAccountList.add(allHOAccountListQuery);
        }

            for(Affiliation_vod__c affRec: allChildAffList)
                for(Account_List_vod__c allHOAccountListInsert : allHOAccountList){
                    if(allHOAccountListInsert.Name_Substring__c.equals(affRec.To_Account_Value__c)){ 
                  //     &&  allAffiliationList.OwnerId.equals(allHOAccountListInsert.OwnerId)){
                        Account_List_Item_vod__c AccListItem = new Account_List_Item_vod__c(
                              Account_List_vod__c = allHOAccountListInsert.Id,
                              Account_vod__c = affRec.From_Account_vod__c
                        );
                        toInsertAcctListItem.add(AccListItem);
                     }
                }

    Database.SaveResult[] srList = Database.insert(toInsertAcctListItem, false);

    for (Database.SaveResult sr: srList){
        if(sr.isSuccess()){
            System.debug('Inserted Account List Item Id: ' + sr.getId());
        } else {
            for(Database.Error err : sr.getErrors()){
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
        }
               }
    }


}//end of Constructor

    public Set<Id> getActiveUsers(){

        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%'
                                             OR Profile_Name_vod__c LIKE '%Eisai_System%') 
                                      AND IsActive = TRUE]); 

        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
}//end of Class

I am receiving an error message like this below:

User-added image

Note: There are many child affiliation record (Parent = False) with 1 To_Account_vod_value(Account Name) and but different From_Account_vod (Person Accounts) So I tried to limit to get only 1 record (To_Account_vod_value) by this line of codes:
 
for (Affiliation_vod__c allAffiliationList : [SELECT ID, OwnerId, Name, From_Account_vod__c, To_Account_Value__c FROM Affiliation_vod__c 
                                                                        WHERE Parent_vod__c = false
                                                                        AND OwnerId IN:getActiveUsers()])
{
    if(!affToAcctValSet.contains(allAffiliationList.To_Account_Value__c)){
          allChildAffList.add(allAffiliationList);
        affToAcctValSet.add(allAffiliationList.To_Account_Value__c);
    }
}

Thanks 
Marion
Hi Experts,

I hope someone can help to convert my class to batch job. This is the first time that I will create a batch job and only a newbie in apex coding.

Here is my class which is working but hitting the DML limit as there are more than 10k to insert.
 
public with sharing class Eisai_AccountListCreation_New {
    
    List<Account_Territory_Mapping__c> allAtmRecs = new List<Account_Territory_Mapping__c>();
    List<Account_List_vod__c> ToInsertAcctList = new List<Account_List_vod__c>();
        
    public Eisai_AccountListCreation_New(){
        
        allAtmRecs = [Select Account_Name_String__c, Account_Owner__c FROM Account_Territory_Mapping__c 
                      												  WHERE Owner_Territory__c LIKE 'EP%' 
                     												  OR Owner_Territory__c LIKE 'QM%'];
        
        for(Account_Territory_Mapping__c  Atm : allAtmRecs){
            if(Atm.Account_Name_String__c != Null && Atm.Account_Owner__c !=Null){
                    Account_List_vod__c AccList = new Account_List_vod__c();
                        AccList.Name = 'HO_' + Atm.Account_Name_String__c;
                        AccList.OwnerId = Atm.Account_Owner__c;
                        ToInsertAcctList.add(AccList);
            }   
        }
        
      System.debug('No of Account List to insert: ' + ToInsertAcctList.size());
        
      Database.insert(ToInsertAcctList,false);

      /*  
      for (Database.SaveResult sr: srList){
            if(sr.isSuccess()){
                System.debug('Inserted Account List count: ' + sr.getId());
            } else {
                for(Database.Error err : sr.getErrors()){
                System.debug(err.getStatusCode() + ': ' + err.getMessage());
                }
            }
       } */
        
    }//End of Constructor

}//End of Class

Below is the batch class which I tried to create but I encountered an error.
 
global class Eisai_BatchInsertAcctList implements Database.batchable<sObject>, Database.Stateful { 
    
    global string query = 'Select Account_Name_String__c, Account_Owner__c FROM Account_Territory_Mapping__c
        															  	   WHERE Account_Name_String__c != Null 
                     												       AND Account_Owner__c !=Null;
                      												  
	global Iterable<sObject> start(Database.BatchableContext info){
        return Database.getQueryLocator(query);
    }
    
	global void execute(Database.BatchableContext info, List<Account_Territory_Mapping__c> scope){
        List<Account_List_vod__c> ToInsertAcctList = new List<Account_List_vod__c>();
        
        for(Account_Territory_Mapping__c  Atm : scope){
            if(Atm.Account_Name_String__c != Null && Atm.Account_Owner__c !=Null){
                    Account_List_vod__c AccList = new Account_List_vod__c();
                        AccList.Name = 'HO_' + Atm.Account_Name_String__c;
                        AccList.OwnerId = Atm.Account_Owner__c;
                        ToInsertAcctList.add(AccList);
            }   
        }
        
    Database.insert(ToInsertAcctList,false);
        
	}
	global void finish(Database.BatchableContext info){
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'marion.c.d.legacion@accenture.com'};
        mail.setToAddresses(toAddresses);
        mail.setSenderDisplayName('Salesforce Support');
        mail.setSubject('Eisai_BatchInsertAcctList Batch Job Run Complete');
            
         System.debug('Insert Account List Count: ' + ToInsertAcctList.size());
           
    }
        
}//end of batch class

Below is the error messasge which I encountered:
User-added image

Thanks,
Marion
public with sharing class Eisai_InsertAcctList_cls {
    
    List<User> usersIdList; 
    Set<Id> usersIdSet = new Set<Id>(); 
    Set<Id> AffFromAcctSet = new Set<Id>(); 
    Set<String> uniqueFieldSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs;
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
	
	//added Collections
	List<Id> fromAcctIdList = new List<Id>();
	List<TSF_vod__c> terr = new List<TSF_vod__c>();
	List<UserTerritory> userTerrInGroupAcct = new List<UserTerritory>();
	Set<String> terrSet = new Set<String>(); 
	Set<Id> terrIdSet = new Set<Id>();
	
    
    public Eisai_InsertAcctList_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE Parent_vod__c = True 
                                                         AND From_Account_RecType__c = 'Group_Practice_Account']);
                                                    //   AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Count '+ allAffParentRecs.size());
		
		//added SOQL Queries
		for(Affiliation_vod__c affFromAcct : allAffParentRecs){
				fromAcctIdList.add(affFromAcct.From_Account_vod__c);
		}
        
		for(TSF_vod__c terr : [SELECT Id, Territory_vod__c, Account_vod__c FROM TSF_vod__c WHERE Account_vod__c IN:fromAcctIdList]){
				terrSet.add(terr.Territory_vod__c);
		}
		
		System.debug('Territory count: ' + terrSet.size());
		
		for(Territory terrId : [SELECT Id, Name FROM Territory WHERE Name IN:terrSet]){
				terrIdSet.add(terrId.Id);
		}
		
		userTerrInGroupAcct = [SELECT TerritoryId, UserId FROM UserTerritory WHERE TerritoryId IN: terrIdSet];
        
        System.debug('No. of user owns the Group Practice Account: ' + userTerrInGroupAcct.size());
        
        //end of added SOQL Queries
		
		
        for(Account_List_vod__c xAcctListRecs  : [Select Name_Populate_Unique_Owner__c FROM Account_List_vod__c 
                                                  									   WHERE Name_Populate_Unique_Owner__c != Null])
                                                  									//   WHERE OwnerId IN: getActiveUsers()])
        {
            uniqueFieldSet.add(xAcctListRecs.Name_Populate_Unique_Owner__c);
        }
        
        for(Affiliation_vod__c allParentAffRecs: allAffParentRecs){
            for(UserTerritory userTerrId : userTerrInGroupAcct){
                if(!AffFromAcctSet.contains(allParentAffRecs.From_Account_vod__c)){
                    Account_List_vod__c AccListRec = new Account_List_vod__c();    
                        AccListRec.Name = 'HO_' + allParentAffRecs.From_Account_Value__c; 
                        AccListRec.Icon_Name_vod__c = '0';  
                        AccListRec.OwnerId = userTerrId.UserId;
                        AffFromAcctSet.add(allParentAffRecs.From_Account_vod__c);
                        newAccListRecList.add(AccListRec);
             	}
        	}
        }
        
        for(Account_List_vod__c accList : newAccListRecList){
            if(!uniqueFieldSet.contains(accList.Name + accList.OwnerId)){
                InsertedAccList.add(accList);
            }
        }
        
        Database.SaveResult[] srList = Database.insert(InsertedAccList, false);

        for (Database.SaveResult sr: srList){
            if(sr.isSuccess()){
                System.debug('Inserted Account List count: ' + sr.getId());
            } else {
                for(Database.Error err : sr.getErrors()){
                System.debug(err.getStatusCode() + ': ' + err.getMessage());
                }
            }
        }
    }//end of 1st block
   
   /*         
   public Set<Id> getActiveUsers(){
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    } */
    
}// End of Class
How can I make the Owner of Account List to be the UserId returned in userTerrInGroupAcct (Set)

Here is the query:
userTerrInGroupAcct = [SELECT TerritoryId, UserId FROM UserTerritory WHERE TerritoryId IN: terrIdSet];

If there are 12 users returned on the query above, there should be 12 Account List created, the OwnerId should be each of the 12 users.

Thanks. 
 
Hi Experts,

I created a class to insert Account List Item Record for every Affiliation child record. 

Here is the code, and it's working in a single record, but when I executed the code manual in developer console I got an error message: 
Error message

Here is my code below: I think I need to use map but I'm just new and still confused on using map.
 
public with sharing class Eisai_InsertAccListItem_cls {
    
    List<Affiliation_vod__c> affChildRecsList;
    List<Account_List_vod__c> acctListInDb;
    List<Account_List_Item_vod__c> newAccListItem = new List<Account_List_Item_vod__c>();
    Set<Id>usersIdSet = new Set<Id>();
    
    public Eisai_InsertAccListItem_cls(){
        
        affChildRecsList = new List<Affiliation_vod__c>([SELECT Id, From_Account_vod__c, To_Account_Value__c, OwnerId
                                                         FROM Affiliation_vod__c 
                                                         WHERE Parent_vod__c = False
                                                         AND OwnerId IN :ActiveUsers()]);
        
            System.debug('Child Affiliation Records count ' + affChildRecsList.size()); 
        
        
        acctListInDb = new List<Account_List_vod__c>([Select Id, Name, OwnerId FROM Account_List_vod__c 
                                                      WHERE OwnerId IN :ActiveUsers()]);
        
            System.debug('Account List Records count ' + acctListInDb.size());
        
        
        
        for(Affiliation_vod__c affChild : affChildRecsList){
            for(Account_List_vod__c acctList : acctListInDb){
               if((acctList.Name.substring(3) == affChild.To_Account_Value__c)
                  && (affChild.OwnerId == acctList.OwnerId)){
                       Account_List_Item_vod__c AccListItem = new Account_List_Item_vod__c();
                       AccListItem.Account_List_vod__c = acctList.Id;
                       AccListItem.Account_vod__c = affChild.From_Account_vod__c;
                       newAccListItem.add(AccListItem);
                 }
             }
         }
   
        
        try{        
            insert newAccListItem ;
            System.debug('New Account List Item Records: ' + newAccListItem);
        }catch(DMLException e){
            System.debug('exeption catch ' + e.getMessage()); 
        }
        
        
    }//End of Constructor   
    
    public Set<Id> ActiveUsers(){
        
       List<User> usersIdList;
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                      OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
    
} //End of Class

Thanks for the help in advance
Hi experts,

I created a class to insert Account List record. The condition is allow duplicate Account List name, but the owner is different from the existing record. 

Example:

Exisiting record:
Account List Name: HO_Test
Owner: Marion Legacion

To be inserted record:
1. Account List Name: HO_Test
   Owner: Marion Legacion
Result: This record cannot be inserted since there is a duplicate both Account List Name and Owner.

2. Account List Name: HO_Test
Owner: Noiram Legacion
Result: A record will be created since Marion Legacion is different from Noiram Legacion.

Note: I created a Unique field to be updated by Workflow to populate the Account List Name and Owner (Formula: Account List Name & OwnerId)


Here is my code which is not working.
 
public with sharing class InsertAccountListRec_TEST_cls {
    
    List<User> usersIdList; 
	Set<Id> usersIdSet = new Set<Id>(); 
	Set<Id> AffFromAcctSet = new Set<Id>(); 
	Set<String> uniqueFieldSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs = new List<Affiliation_vod__c>();
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
    
    public InsertAccountListRec_TEST_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE (From_Account_vod__r.Id = '0011200001GNrb0AAD' AND Parent_vod__c = True) 
														 AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Count '+ allAffParentRecs.size());
		
        for(Account_List_vod__c xAcctListRecs  : [Select OwnerId, Unique_Owner_Name__c FROM Account_List_vod__c 
                                                  WHERE Name = 'HO_RADY\'S CHILDREN\'S UCSD'
                                                  AND OwnerId IN: getActiveUsers()])
        {
            uniqueFieldSet.add(xAcctListRecs.Unique_Owner_Name__c);
        }
        
        for(Affiliation_vod__c allParentAffRecs: allAffParentRecs){
            if(!AffFromAcctSet.contains(allParentAffRecs.From_Account_vod__c)){
                Account_List_vod__c AccListRec = new Account_List_vod__c();    
                AccListRec.Name = 'HO_' + allParentAffRecs.From_Account_Value__c; 
                AccListRec.Icon_Name_vod__c = '0';	
                AccListRec.OwnerId = allParentAffRecs.OwnerId;
                AffFromAcctSet.add(allParentAffRecs.From_Account_vod__c);
                newAccListRecList.add(AccListRec);
            } 
        }
        for(Account_List_vod__c accList : newAccListRecList){
            if(!uniqueFieldSet.contains(accList.Name + accList.OwnerId)){
                InsertedAccList.add(accList);
            }
        }
        
        try{        
            insert InsertedAccList ;
            System.debug('New Account List Records: ' + InsertedAccList);
        }catch(DMLException e){
            System.debug('exeption catch ' + e.getMessage()); 
        }
    }//end of 1st block
    
    public Set<Id> getActiveUsers(){
        
        usersIdList = new List<User>([SELECT Id
                                      FROM User
                                      WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                             OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                      AND IsActive = TRUE]); 
        
        for(User users : usersIdList){
            usersIdSet.add(users.Id);  
        }
        return usersIdSet;
    }
}// End of Class

Unique_Owner_Name__c - is the unique field.

I queried all the Unique_Owner_Name__c field of all Account List record and I checked the unique field set to see if the (accList.Name + accList.OwnerId) is existing, if not then add the Account List record to a list and DML Insert

Please help

Thanks
Marion
 
Hi, 

Can somebody help me with the logic on the following: 

Account List name is existing, but the ownerid is not existing (Different user)  -> insert ok
Account List name is not existing, but owner id is existing in db - insert ok 

Account List name is existing, owner id is existing (Avoid duplicate record with the same Account List name with the same owner)  -> No insert

Basically, I just want to prevent the record to be inserted if the account list name is duplicate and also the same owner, but if the account list has a match in the database, but it's owner is different, it's should be inserted.


Here is my current code: 
 
public with sharing class InsertAccountListRec_TEST_cls {
    
    List<User> usersIdList;
    Set<Id> usersIdSet = new Set<Id>();
    Set<Id> AffFromAcctSet = new Set<Id>();
    Set<Id> xAcctListOidSet = new Set<Id>();
    Set<String> xAcctListNameSet = new Set<String>();
    List<Affiliation_vod__c> allAffParentRecs = new List<Affiliation_vod__c>();
    List<Account_List_vod__c> newAccListRecList = new List <Account_List_vod__c>();
    List<Account_List_vod__c> xAcctListRecs = new List <Account_List_vod__c>();
    List<Account_List_vod__c> InsertedAccList = new List <Account_List_vod__c>();
    
    
    
    //Creation a list of all Parent Affiliation Records, then add to allParentRecsSet (SET).
    //Start of 1st Block
    public InsertAccountListRec_TEST_cls(){
        allAffParentRecs = new List<Affiliation_vod__c>([SELECT Id, OwnerId, From_Account_vod__c, From_Account_Value__c, To_Account_vod__c
                                                         FROM Affiliation_vod__c
                                                         WHERE (From_Account_vod__r.Id = '0011200001GNrb0AAD' 
                                                         AND Parent_vod__c = True)
                                                         AND OwnerId IN: getActiveUsers()]);
        
        System.debug('Parent Affiliation Record Count '+ allAffParentRecs.size());
        
        
        for(Account_List_vod__c xAcctListRecs  : [Select OwnerId, Name FROM Account_List_vod__c 
                                                  WHERE Name LIKE 'HO_%'
                                                  AND OwnerId IN: getActiveUsers()]){
                                                                      xAcctListOidSet.add(xAcctListRecs.OwnerId);
                                                      				  xAcctListNameSet.add(xAcctListRecs.Name);
                                                                  }
        
        System.debug('Account List Record Count '+ xAcctListRecs);
        
        for(Affiliation_vod__c allParentAffRecs: allAffParentRecs){
            if(!AffFromAcctSet.contains(allParentAffRecs.From_Account_vod__c)){
                Account_List_vod__c AccListRec = new Account_List_vod__c();    
                AccListRec.Name = 'HO_' + allParentAffRecs.From_Account_Value__c; 
                AccListRec.Icon_Name_vod__c = '0';	
                AccListRec.OwnerId = allParentAffRecs.OwnerId;
                AffFromAcctSet.add(allParentAffRecs.From_Account_vod__c);
                newAccListRecList.add(AccListRec); 
            }
        }
               
         for(Account_List_vod__c acctListToCreate : newAccListRecList){
             if(xAcctListNameSet.contains(acctListToCreate.Name) && !xAcctListOidSet.contains(acctListToCreate.OwnerId)){
                       InsertedAccList.add(acctListToCreate);
             }     
         }	
               
               insert InsertedAccList ;
               System.debug('New Account List Records: ' + InsertedAccList);
	}//end of 1st block
    
    
    public Set<Id> getActiveUsers(){
    
            usersIdList = new List<User>([SELECT Id
                                     FROM User
                                     WHERE (Profile_Name_vod__c LIKE '%Eisai_Epilepsy%' 
                                     OR Profile_Name_vod__c LIKE '%Eisai_PrimaryCare%') 
                                     AND IsActive = TRUE]); 
        
            for(User users : usersIdList){
                    usersIdSet.add(users.Id);  
            }
        return usersIdSet;
    }
}// End of Class
The logic which is not working is in line 47 to 51

Thanks for the help..