Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
Trigger:
trigger OneConPerAcc 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 then one Contact for this account');
}
}
}
I hope it helps you.
Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.
Thanks for your code. It clarified my doubt. Could you please exlain it in brief. Like I have few queries like in what purposes do we use MAP. And we cannot use MAP for before Insert right?Then can we use it in Handler class? And also explain the usage of two for loops.
This will solve your problem and addittionaly this will help you on UNDELTE event of a contact as well.
Trigger Code
trigger ONECONTACT on Contact (before insert,after unDelete) {
OneContact.onecontactmethod((Trigger.isInsert || Trigger.isUndelete)? Trigger.New : Trigger.Old);
}
Trigger Handler
public class OneContact {
public static void onecontactmethod(List<Contact> conlist){
Set<Id> accIds = New Set<Id>();
for(Contact con : conlist){
if(con.AccountId != null){
accIds.add(con.AccountId);
}
}
if(accIds != null){
List<Contact> conL = New List<Contact>([SELECT Id,Name,AccountID FROM Contact WHERE AccountID IN :accIds]);
if(conL.size() > 0 ){
for(Contact con :conlist){
con.adderror('you can not add more than one Contact to this account');
}
}
}
}
}
Please mark it as best answer if it solves your issue .
Greetings to you!
Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
Trigger:
I hope it helps you.
Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.
Thanks and Regards,
Khan Anas
Thanks for your code. It clarified my doubt. Could you please exlain it in brief. Like I have few queries like in what purposes do we use MAP. And we cannot use MAP for before Insert right?Then can we use it in Handler class? And also explain the usage of two for loops.
Regards,
Jyotsna
This will solve your problem and addittionaly this will help you on UNDELTE event of a contact as well.
Please mark it as best answer if it solves your issue .