You need to sign in to do that
Don't have an account?
Syed Ahmed 10
Contact ID Trigger not working on Update
I have made a custom field Contact ID to capture the Contact ID for person accounts. So to acheive this i have made a trigger, the trigger is working fine on insert but on before update its not working. Please let me know what am i doing wrong.
trigger UpdateContactID on Account (after insert, before update)
{
List<Contact> contactList;
if ((trigger.isInsert) || (trigger.isUpdate && trigger.new[0].Contact_ID__c == null))
{
List<String> newAccountIDList = new List<String>();
// Taking all account IDs in collection
for(Account acct: Trigger.new)
{
newAccountIDList.add(acct.ID);
}
// Fetching contacts against the account IDs
try {
contactList = [SELECT Id, Account.Id FROM Contact WHERE Account.ID in :newAccountIDList and Account.IsPersonAccount = true];
} catch(exception ex){
system.debug('UpdateContactID error - cant find Contact record:' + ex);
}
// Adding contacts in a map with relation to Account ID
Map<String, Contact> mapContact = new Map<String, Contact>();
for(Contact cont : contactList)
{
mapContact.put(cont.Account.Id, cont) ;
}
if(!mapContact.values().isEmpty())
{
// Updating Contact_ID__c from Map to new Account list to update
List<Account> toUpdate = new List<Account>();
for(Contact con: contactList)
{
toUpdate.add(new Account(
id = con.Account.Id,
Contact_ID__c = con.Id
));
}
if (trigger.isInsert)
{
update toUpdate;
}
}
}
}
trigger UpdateContactID on Account (after insert, before update)
{
List<Contact> contactList;
if ((trigger.isInsert) || (trigger.isUpdate && trigger.new[0].Contact_ID__c == null))
{
List<String> newAccountIDList = new List<String>();
// Taking all account IDs in collection
for(Account acct: Trigger.new)
{
newAccountIDList.add(acct.ID);
}
// Fetching contacts against the account IDs
try {
contactList = [SELECT Id, Account.Id FROM Contact WHERE Account.ID in :newAccountIDList and Account.IsPersonAccount = true];
} catch(exception ex){
system.debug('UpdateContactID error - cant find Contact record:' + ex);
}
// Adding contacts in a map with relation to Account ID
Map<String, Contact> mapContact = new Map<String, Contact>();
for(Contact cont : contactList)
{
mapContact.put(cont.Account.Id, cont) ;
}
if(!mapContact.values().isEmpty())
{
// Updating Contact_ID__c from Map to new Account list to update
List<Account> toUpdate = new List<Account>();
for(Contact con: contactList)
{
toUpdate.add(new Account(
id = con.Account.Id,
Contact_ID__c = con.Id
));
}
if (trigger.isInsert)
{
update toUpdate;
}
}
}
}
You are using a check before update statement that is causing problem.
If you want to learn more about triggers refer to below link.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_context_variables_considerations.htm
Please mark this as solution if this solves your problem, So that if anyone has this issue this post can help