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
ABC XYZ 39ABC XYZ 39 

Can't get this simple piece of code of work : Contact.lastname should not be equal to Account Name in Apex Class? Please help

Basic Logic is : Every new contact of record type 'customer' will be inserted into q Queue object. Additional logic is the new contact won't be inserted into the Queue if Contact's last name is not qual to Account Name. This is what I am unable to implement. I have tried to use this condition everywhere in the logic. It simple does not work. I am new to Apex programming. Please help. 

Logic :
public static void processNewContact(Map<Id, Contact> newContactMap, Map<Id, Contact> oldContactMap) { 
                List<Queue__c> objList = new List<Queue__c>();    
                Map<id, recordtype> contactRecTypeMap = new Map<id, recordType>([select id from Recordtype where SobjectType='Contact' and Name = 'Customer']);
                     if(contactRecTypeMap!=null ){
                    System.debug('RECORDTYPES RETRIEVED>>>' + contactRecTypeMap + 'size>>>' + contactRecTypeMap.size());
              //   if(contact.account.name!=contact.lastname) {
                    for(Contact c: newContactMap.values()) {  
                  //   if(c.account.name!=c.lastname) {
                    System.debug('checking for last name and account name entry >>>> If Loop1 >>' + c.lastname + c.account.name);
                   //   if(c.account.name!=null && c.lastname!=c.account.name) {
      //   if(c.lastname!=c.account.name) {
             if(contactRecTypeMap !=null && contactRecTypeMap.keySet().contains(c.recordtypeID)){   
            //    if(c.lastname!=c.account.name) {
                  Queue__c q1 = new Queue__c();
                         q1.Object_Name__c='Contact';
                         q1.Description__c= 'New Contact';
                         q.Record_Id__c = C.Id;
                          q1.Notification_Timestamp__c= c.CreatedDate;
                          
                         /*   if(c.lastname!=c.account.name) {
                  objList.add(obj1);
                
                          }
                         
                         else {
                         
                         delete objList;
                         
                         }  */
        
                         
                        }  
              //   }
                     
                 //  }
              }
       
                           }
         
         }
Best Answer chosen by ABC XYZ 39
Nayana KNayana K
public static void processNewContact(Map<Id, Contact> newContactMap, Map<Id, Contact> oldContactMap) 
{ 
    List<Queue__c> lstQ = new List<Queue__c>();    
	Id idContactCustomerRecType;
	Map<Id, String> mapIdToAccountName = new Map<Id, String>();
	
	// Assuming Developer Name is 'Customer'
	List<RecordType> lstRecType = new List<RecordType>([SELECT Id FROM RecordType WHERE DeveloperName = 'Customer' AND SobjectType = 'Contact']);
	if(!lstRecType.isEmpty())
		idContactCustomerRecType = lstRecType[0].Id;
		
	if(idContactCustomerRecType != null)
	{
		// we can;t fetch parent fields directly, so collect account Ids first
		for(Contact objContact : newContactMap.values())
		{
			if(objContact.AccountId != null)
				mapIdToAccountName.put(objContact.AccountId, null);
		}
	}
	
	// iterate over account with matching collected Ids and fetch names
	for(Account objAccount : [SELECT Id, Name FROM Account WHERE Id IN : mapIdToAccountName.keySet()])
	{
		mapIdToAccountName.get(objAccount.Id, objAccount.Name);
	}
	
	// loop again to perform business logic
	for(Contact objContact : newContactMap.values())
	{
		/* 1. If Contact RecordType is Customer AND if LastName != Account.Name, insert Queue **/
		if(objContact.RecordTypeId == idContactCustomerRecType && objContact.AccountId != null && objContact.LastName != mapIdToAccountName.get(objContact.AccountId))
		{
			Queue__c objQ = new Queue__c();
			objQ.Object_Name__c='Contact';
			objQ.Description__c= 'New Contact';
			objQ.Record_Id__c = objContact.Id;
			objQ.Notification_Timestamp__c= objContact.CreatedDate;
			lstQ.add(objQ);
		}
			
	}
	
	if(!lstQ.isEmpty())
		insert lstQ;
	
}

 

All Answers

ABC XYZ 39ABC XYZ 39
Anther condition is : Account Name associated with a Contact cannot be null.  (contact.account name)
Nayana KNayana K
public static void processNewContact(Map<Id, Contact> newContactMap, Map<Id, Contact> oldContactMap) 
{ 
    List<Queue__c> lstQ = new List<Queue__c>();    
	Id idContactCustomerRecType;
	Map<Id, String> mapIdToAccountName = new Map<Id, String>();
	
	// Assuming Developer Name is 'Customer'
	List<RecordType> lstRecType = new List<RecordType>([SELECT Id FROM RecordType WHERE DeveloperName = 'Customer' AND SobjectType = 'Contact']);
	if(!lstRecType.isEmpty())
		idContactCustomerRecType = lstRecType[0].Id;
		
	if(idContactCustomerRecType != null)
	{
		// we can;t fetch parent fields directly, so collect account Ids first
		for(Contact objContact : newContactMap.values())
		{
			if(objContact.AccountId != null)
				mapIdToAccountName.put(objContact.AccountId, null);
		}
	}
	
	// iterate over account with matching collected Ids and fetch names
	for(Account objAccount : [SELECT Id, Name FROM Account WHERE Id IN : mapIdToAccountName.keySet()])
	{
		mapIdToAccountName.get(objAccount.Id, objAccount.Name);
	}
	
	// loop again to perform business logic
	for(Contact objContact : newContactMap.values())
	{
		/* 1. If Contact RecordType is Customer AND if LastName != Account.Name, insert Queue **/
		if(objContact.RecordTypeId == idContactCustomerRecType && objContact.AccountId != null && objContact.LastName != mapIdToAccountName.get(objContact.AccountId))
		{
			Queue__c objQ = new Queue__c();
			objQ.Object_Name__c='Contact';
			objQ.Description__c= 'New Contact';
			objQ.Record_Id__c = objContact.Id;
			objQ.Notification_Timestamp__c= objContact.CreatedDate;
			lstQ.add(objQ);
		}
			
	}
	
	if(!lstQ.isEmpty())
		insert lstQ;
	
}

 
This was selected as the best answer
ABC XYZ 39ABC XYZ 39
Thank you fot your response. Can you please help me with the test class? 
ABC XYZ 39ABC XYZ 39
I am getting this error.

Error: Compile Error: Method does not exist or incorrect signature: [Map<Id,String>].get(Id, String) for  mapIdToAccountName.get(objAccount.Id, objAccount.Name);

how to resolve it?
Nayana KNayana K
change 'get' to 'put' like this : mapIdToAccountName.put(objAccount.Id, objAccount.Name);

Extremely sorry for this.
ABC XYZ 39ABC XYZ 39
Thank you Nayana. It worked. can you please help me with the test class? 
Nayana KNayana K
Please mark this answer as solved
Nayana KNayana K
@isTest
public with sharing class ContactTriggerTest 
{
    
    @IsTest
    static void testForContactInsert()
    {
        Id idCustomerContactRecType = [SELECT Id FROM RecordType WHERE SobjectType = 'Contact' AND DeveloperName = 'Customer'].Id;
        
        // insert Account 
        Account objAccount = new Account(Name = 'Test Acc', RecordTypeId = idCustomerContactRecType);
        insert objAccount;
        
        // insert Contact 
        List<Contact> lstContact = new List<Contact>{	new Contact( LastName = 'Test Con1', AccountId = objAccount.Id),
														new Contact( LastName = 'Test Con2', AccountId = objAccount.Id),
														new Contact( LastName = 'Test Con3', AccountId = objAccount.Id)
													};
        insert lstContact;
        
		// verify if 3queues are created corresponding to 3 contacts
		system.assertEquals(3, [SELECT COUNT() FROM Queue__c]);
        
    }
    
}

 
ABC XYZ 39ABC XYZ 39
Thank you Nayana.

I have another similar scenario like the one I discussed. This is an update scenario
Logic : 
If contact record type is 'Customer'  --then check whether record has been modified by 'X' user --> If the record has been modified --> Check whether A,B,C field values have changes ---> If the field values have changed --> Then, insert into the Queue object

How can I best write a test class for this scenario? Please assist. Thanks.