+ Start a Discussion
Bryan CerratiBryan Cerrati 

updating accross objects

i am trying to update a date field on my contacts that are marked as "admin Contacts" everytime a matching date field on my accounts are updated. 

Class:
public with sharing class AdminUsersAccount
	{
		public void leadAlerts(List<Account> lstAcct)
		{
			sendAlertsPrivate(lstAcct);
		}
	
		private void sendAlertsPrivate(List<Account> lstAcct)
		{
			List<Contact> lstUpdateCon = new List<Contact>();
			
			Set<Id> accID = new Set<Id>();
			for (Account a : lstAcct)
				accID.add(a.Id);	
			map<Id, Contact> conMap = new map<Id, Contact>([SELECT Id, Admin_User__c, Account_Expiration__c FROM Contact WHERE Admin_User__c = true AND AccountId IN :accID]);
	
			for(Account acc : lstAcct)
			{	
				
				if(conMap.containsKey(acc.Id))
				{
					if(acc.Approved_Date__c != null)
					{
						Date tdy = date.today();
						Date expire = acc.Approved_Date__c.addDays(365);
						boolean approved = expire >= tdy;
						lstUpdateCon.add(new Contact(Account_Expiration__c = approved?conMap.get(acc.Id).Account_Expiration__c: null));
					}
					else
					{
						lstUpdateCon.add(new Contact(Account_Expiration__c = null));
					}
				}
			}
			if(!lstUpdateCon.isEmpty())
				update lstUpdateCon;		
		}
	}

Trigger:
 
trigger AdminUsersAccountTrigger on Account (after update) 
	{
		AdminUsersAccount objAcctHandler = new AdminUsersAccount();
		
		if (Trigger.IsUpdate)
		{
			objAcctHandler.leadAlerts(Trigger.New);
		}
	    
	}

im really not sure where this is going wrong... i get no errors but nothing happens when updating the field on the account. 
AjazAjaz
Hey Bryan,

The problem lies here on the line 20. if(conMap.containsKey(acc.Id))

The conMap has a key value pair of contactID and contact record, but on line 20, you are checking if conMap contains a key with ID of accountID which will always fail.

So to meet your requirement, you gonna have to add a key of accountID in conMap rather than contactID. This will solve your problem.

Give a thumbsup if this helped you.

Regards,
Zaja
Bryan CerratiBryan Cerrati
im not sure what you mean? 

does the map i provided add the contact ID or the accId in the mapping of ID?
map<Id, Contact> conMap = new map<Id, Contact>([SELECT Id, Admin_User__c, Account_Expiration__c FROM Contact WHERE Admin_User__c = true AND AccountId IN :accID]);
if thats the case how can i map the contact with the accountId?
 
Bryan CerratiBryan Cerrati
map<Id, Contact> conMap = new map<Id, Contact>();
		for(Account a : lstAcct)
		{
			conMap.put(a.Id, null);
		}
		conMap.remove(null);
		List<Contact> sobjCon = new List<Contact>([SELECT Id, Admin_User__c, Account_Expiration__c FROM Contact WHERE Admin_User__c = true AND AccountId In : conMap.keySet()]);
		conMap.putAll(sobjCon);

still cant solve this issue...