+ Start a Discussion
fahad shaikh 22fahad shaikh 22 

FOR(ACCOUNT A1:[SELECT ID,NAME,(SELECT ID,NAME FROM CONTACTS)FROM ACCOUNT WHERE ID IN:ACCID]){ IF(A1.CONTACTS.SIZE ()>5) { for(contact c:trigger.new) c.accountid.ADDERROR('YOU CAN NOT ADD MORE THAN 5 CONTACTS IN A ACCOUNT');

what is wrong in it
 
fahad shaikh 22fahad shaikh 22
// write a trigger if we add more than 5 contact in a account it should throw error

trigger LIMIT_CONTACT on Contact (before insert,before update,after undelete) {
    SET<ID> ACCID= NEW SET<ID>();
    LIST <CONTACT> MYCON_LIST=[SELECT ID, NAME,ACCOUNTID FROM CONTACT];
    FOR (CONTACT CON :MYCON_LIST){
        ACCID.ADD(CON.ACCOUNTID);
    }
    FOR(ACCOUNT A1:[SELECT ID,NAME,(SELECT ID,NAME FROM CONTACTS)FROM ACCOUNT WHERE ID IN:ACCID]){
        IF(A1.CONTACTS.SIZE ()>5) {
            for(contact c:trigger.new)
          c.accountid.ADDERROR('YOU CAN NOT ADD MORE THAN 5 CONTACTS IN A ACCOUNT');  
        } 
    }
}


// with this logic i am not able to add a single related contact in account
SarvaniSarvani
Hi Fahad,

I tested your code and everything seems to be fine. I was able to see the error using your code, the only thing I changed was in line 8 as below adding "=" in condition check.
IF(A1.CONTACTS.SIZE()>=5) {
Did you check if you have any other triggers or automated processes on contact object which are restircting addition of new record ? 

Hope this helps! Please mark as best if it solves your issue

Thanks
fahad shaikh 22fahad shaikh 22
Hi Sarvani,
got the right answer the answer is--


// write a trigger if we add more than 5 contact in a account it should throw error

trigger LIMIT_CONTACT on Contact (before insert,before update) {
    SET<ID> ACCID= NEW SET<ID>();
    FOR (CONTACT CON :trigger.new){
    if(con.accountid!=null){
        ACCID.ADD(CON.ACCOUNTID);
        }
    }
    FOR(ACCOUNT A1:[SELECT ID,NAME,(SELECT ID,NAME FROM CONTACTS)FROM ACCOUNT WHERE ID IN:ACCID]){
        IF(A1.CONTACTS.SIZE ()>5) {
            for(contact c:trigger.new){
          c.ADDERROR('YOU CAN NOT ADD MORE THAN 5 CONTACTS IN A ACCOUNT'); 
}         
        } 
    }
}