I have a custom checkbox infront of every related contact.That checkbox is to make a contact primary.I have written a trigger if there is more than one primary contact than i should display an error..i have a requirement now like if there is only one primary contact ,than the trigger should copy the contact email address to custom email address field on account tab.Can someone gimme a heads up?
the trigger that i have written below ensure that only one primary contact must be there but it does not copy that primary's contacts email address to custom email address on account tab
below is my trigger:
trigger checkPrimaryField on Contact (before insert,before update)
{
list <contact> listcon= new list<contact>();
String accID;
integer count=0;
for(contact c:Trigger.new )
{
accid = c.accountid;
}
listcon = [SELECT AccountId,Primary_Contact__c FROM Contact WHERE Primary_Contact__c = true AND AccountId = :accid];
for(contact c : listcon)
{
if(c.Primary_Contact__c)
{
count = count+1;
}
}
system.debug('count is ::'+count);
if(count>1)
trigger.new[0].adderror('................');
if(count >=1)
{
list <contact> d = [SELECT AccountId,Primary_Contact__c FROM Contact WHERE Primary_Contact__c = true];
Map<Id, Account> m = new Map<Id, Account>();
for(Contact c : d)
{
if (Trigger.newMap.get(c.Id).Primary_Contact__c= true)
{
m.put(c.AccountId, new Account(Id = c.AccountId, Account_Email__c = c.Email));
}
}
update m.values();
}
}