0 replies i want to insert contact records to account.but i want to insert only one contact to one account. is there any 2 contacts for one account i want to throw an error. can anybody help me on this ?
Yeah, You can create rolluop summary field on Account object to Count #of child Contact records, Then put a validation rule on the rollup summary field ,if count > 2 then throw error.
Else you can go with the triggers too, if you are interested in coding.
Below code can fullfill your requirements. Hope this will work for you.
trigger FindDuplicateContact on Contact (before insert) {
List<id> accId = new List<id>(); for(contact cc : trigger.new){ if(cc.AccountId != null){ accId.add(cc.AccountId); } } List<contact> ccList = new List<contact> ();
List<Account> accLst = [select id,(select id from contacts) from account where id IN : accId] ; for(account accObj : accLst ){ for(contact c : accObj.contacts){ ccList.add(c); } }
for(contact oCon:trigger.new) if(ccList.size() > 0 ){ oCon.addError('you can not add more than one contact for this account');
} }
Please mark this as best answer if this solves your problem.
You can create rolluop summary field on Account object to Count #of child Contact records,
Then put a validation rule on the rollup summary field ,if count > 2 then throw error.
Else you can go with the triggers too, if you are interested in coding.
Below code can fullfill your requirements. Hope this will work for you.
trigger FindDuplicateContact on Contact (before insert) {
List<id> accId = new List<id>();
for(contact cc : trigger.new){
if(cc.AccountId != null){
accId.add(cc.AccountId);
}
}
List<contact> ccList = new List<contact> ();
List<Account> accLst = [select id,(select id from contacts) from account where id IN : accId] ;
for(account accObj : accLst ){
for(contact c : accObj.contacts){
ccList.add(c);
}
}
for(contact oCon:trigger.new)
if(ccList.size() > 0 ){
oCon.addError('you can not add more than one contact for this account');
}
}
Please mark this as best answer if this solves your problem.
Thank you
Ajay Dubedi