function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
brahmanaidubrahmanaidu 

Deleting the contact when the accountid is null

trigger ContactTrigger on Contact (before update) {
    set<id> ids=new set<id>();
    if(Trigger.isUpdate){
        for(Contact con:Trigger.new){
            if(con.AccountId==null){
                ids.add(con.Id);
            }
        }
    }
    List<Contact> condata=[select Id,Name from Contact where Id in:ids];
    if(condata.size()>0&& condata!=null){
        
    }
     delete condata;    
}
bhanu_prakashbhanu_prakash
Hi Brahma,
 
trigger ContactTrigger on Account(before delete) {
    List < Account > accList = new List < Account > ();
    Set < id > accIdSet = new Set < id > ();
    for (Account acc: Trigger.old) {
        accIdSet.add(acc.id);
    }

    Map < Id, Account > accts = new Map < Id, Account > ([Select Id, (Select Id from contacts) from Account where id in: accIdSet]);

    for (Account acc: Trigger.old) {
        if (accts.get(acc.id).contacts.size() > 0) {
            acc.adderror('Account cannot be deleted');
        }
    }

}

Thanks, 
Bhanu Prakash
visit ForceLearn (https://www.forcelearn.com)for salesforce Latest Updates and development tips

let us know if it helps you and mark it best if it helps you
Amit Chaudhary 8Amit Chaudhary 8
Try to update your code like below
trigger ContactTrigger on Contact (After insert,After Update)
{
    set<id> ids=new set<id>();
    
        for(Contact con:Trigger.new){
            if(con.AccountId==null){
                ids.add(con.Id);
            }
        }
    List<Contact> condata=[select Id,Name from Contact where Id in:ids];
    if(condata.size()>0 && condata != null )
	{
		delete condata;
    }
}

Let us know if this will help you