+ Start a Discussion
Deepak Pandey 13Deepak Pandey 13 

apex trigger if account checkbox is checked than contact will not inserted show error

If account checkbox is checked than contact will not inserted show error?
trigger avoid on contact (before insert,before update)
{
   set<id> setcheck = new set<id>();
   set<id> setExistingid = new set<id>();

   //Add alll email in set to fetch related existing records
   list<account> lst=[select id ,name,checkcontact__c from account where checkcontact__c=true];
   system.debug('$$$$lst' +lst);
   for(Account acc : lst)
   {
          setcheck.add(acc.id);
          system.debug('$$$$setcheck' +setcheck);
   }

   if(Trigger.isInsert||Trigger.isUpdate)
     for(contact a:trigger.new)
     {
         if(setExistingid.contains(a.account.id))
        {
                 a.adderror('This checkcontact ');
        }
     }
}
Pankaj_GanwaniPankaj_Ganwani
trigger avoid on contact (before insert,before update)
{
   set<id> setcheck = new set<id>();
   set<id> setExistingid = new set<id>();

   //Add alll email in set to fetch related existing records
   list<account> lst=[select id ,name,checkcontact__c from account where checkcontact__c=true];
   system.debug('$$$$lst' +lst);
   for(Account acc : lst)
   {
          setcheck.add(acc.id);
          system.debug('$$$$setcheck' +setcheck);
   }

   if(Trigger.isInsert||Trigger.isUpdate)
     for(contact a:trigger.new)
     {
         if(setExistingid.contains(a.accountid))
        {
                 a.adderror('This checkcontact');
        }
     }
}

Please use above mentioned code.
Deepak Pandey 13Deepak Pandey 13
trigger avoiding on contact (before insert,before update)
{
   set<id> setcheck = new set<id>();
  
   list<account> lst=[select id ,name,checkcontact__c from account where checkcontact__c=true];
   system.debug('$$$$lst' +lst);
   for(Account acc : lst)
   {
          setcheck.add(acc.id);
          system.debug('$$$$setcheck' +setcheck);
   }

   if(Trigger.isInsert||Trigger.isUpdate)
     for(contact a:trigger.new)
     {
         if(setcheck.contains(a.accountid))
        {
                 a.adderror('not to fill account if field checked ');
        }
     }
}
Deepak Pandey 13Deepak Pandey 13
but it is not bulkified..
Pankaj_GanwaniPankaj_Ganwani
This should be. Did you get a chance to check with bulk data?