My requirement is I can only be able to add new contact under account when Account field name check__c is true. If its not true than Error should be pop up like in active account. I tried below code but still not able to get the result. Any help please?

trigger check1 on Contact (after insert,after update,after delete) {
set<Id> AccIds = new set<Id>();
 if(trigger.isinsert || trigger.isupdate)
     for(Contact c:Trigger.new)

 if(trigger.isdelete || trigger.isupdate)
     for(contact c2:Trigger.old)

 check m = new check();


public class check
    list<Account> Accounts = new list<Account>();
    list<Account> Accountstoupdate = new list<Account>();

    public void checkc(set<Id> AccIds)
        Accounts=[select Id,check__c,(select Id from Contacts ) from Account where Id IN :AccIds];

         for (Account ac : Accounts) {
        if(ac.check__c == true){



       ac.addError('Account in not active');


        update Accountstoupdate;

1 Answer 1


This could be much simpler -- and you can take advantage of implicit DML in the before insert trigger handling

trigger validContact on Contact (before insert) {

  set<ID> aIdSet = new set<ID> ();
  for (Contact c: Trigger.new)   // collect parent account ids to search 

  // fetch Accounts as they are not implictly in trigger. save in EZ lookup map
  map<ID,Account> aIdToAccountMap = new map<ID,Account> ([select id, check__c
                                      from Account where ID IN: aIdSet]);

  for (Contact c: Trigger.new) // now, error those in trigger without parent account check true
     if (c.AccountId != null &&  // poss to have Contacts w/o accounts 
         !aIdToAccountMap.get(c.AccountId).Check__c) // inactive account per OP
        c.addError('Account is not active, contact can\'t be added');

Now, all that said, I'd invest in a trigger framework or, better yet, the Separation of Concerns pattern but those are topics beyond what you probably need here

  • Thank you for your reply, I just need to add this trigger or any other class i have to write with this, tried this one but getting error like Illegal assignment from Set<Id> to List<Id> at line 3 column 8 Dec 8, 2016 at 6:24
  • oops - my bad; fixed line 3
    – cropredy
    Dec 8, 2016 at 6:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .