I have 3 record Types 1.tender partner 2.Bidder 3.sales manager In contact object. Contact object having lookup relationship with Account object. I want to store only One Record for Tender partner contact per Account. For that same account another tender partner Record should not insert.Rest Record type Contact have no restriction per Account.
I have written trigger for that And executing well.At the time of testing i have created 1 each records for all 3 record types for same account .after that trying to insert one more contact for Tender partner type then Trigger executed well. But when i deleted tender partner Contact and again want to insert new tender partner contact at that time error executes. Help me to overcome this.
trigger AllowMaxOneContactPerAccountTrigger on Contact (before insert) {
set<id> AccIdSet = new set<id>();
map<id,Contact> Conmap = new map<id,Contact>();
for(contact objcon : trigger.new){
if(objcon.AccountId != null){
AccIdSet.add(objcon.AccountId);
}
}
if(!AccIdSet.isEmpty()){
for(Contact objContact : [select id,AccountId,RecordTypeId from contact where AccountId IN:AccIdSet]){
Conmap.put(objContact.AccountId,objContact);
}
}
if(!Conmap.isEmpty()){
for(contact objcon : trigger.new){
if(Conmap.containsKey(objcon.AccountId)){
if(objcon.RecordTypeId == [select id,Name from RecordType where Name='Tender partner'].Id){
objcon.adderror('Only one Tender partner is Allowed per Account');
}
}
}
}
}
Ruchit Patel (Cognizant) Forum Ambassador
Hello Chetan, Please try the revised version of your code
trigger AllowMaxOneContactPerAccountTrigger on Contact (before insert) {
set<id> AccIdSet = new set<id>();
for(contact objcon : trigger.new){
if(objcon.AccountId != null){
AccIdSet.add(objcon.AccountId);
}
}
string conRecId = [select id,Name from RecordType where Name='Tender partner'].Id;
Map<string,List<Contact>> accVsConIdMap = new Map<string,List<Contact>>();
if(!AccIdSet.isEmpty()) {
if(conRecId.isNotEmpty()) {
for(Contact con : [select id, AccountId, RecordTypeId from contact where recordTypeId = :conRecId AND accountId IN: AccIdSet]){
if(!accVsConIdMap.containskey(con.AccountId))
accVsConIdMap.put(con.AccountId, new list<contact>());
accVsConIdMap.get(con.AccountId).add(con);
}
}
}
if(!accVsConIdMap.isEmpty()) {
for(contact objcon : trigger.new) {
if(accVsConIdMap.containskey(objcon.AccountId) && accVsConIdMap.get(objcon).size() > 0) {
objcon.adderror('Only one Tender partner is Allowed per Account');
}
}
}
}