+ Start a Discussion
sk aleemsk aleem 

write a trigger when a new Contact is inserted with out Account then throw error message

ChetanGChetanG
Hi @aleem : You can use Validation rule on contact instead of a Trigger 
Deepali KulshresthaDeepali Kulshrestha
Hi Aleem,

Try the following it works according to your requirement:
Trigger:
trigger ContactTrigger on Contact (before insert) {
if(trigger.isBefore && trigger.isInsert){
                InsertContact.contactMethod(trigger.new);
        }
}
Trigger-Handler:
public class InsertContact {
public static void contactMethod(List<Contact> ConList){
    
        try{
            for(Contact con:ConList){
            if(con.AccountId==null){
                con.addError('Please add account to this contact.');
            }
            }
        }
        catch(Exception e){
            system.debug('Line_no---->'+e.getLineNumber()+'Message-->'+e.getMessage());
        }
        
        }
        }

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
Ajay K DubediAjay K Dubedi
Hi SK,
Please try the below code it had completed trailhead challenge on my Org and let me know if this works for you. If still need modifications do let me know.
 
Apex Class:
 
public class ContactInsert {
    public static void insertContact(List<Contact> conList) {
        for(Contact conObj : conList){
            if(conObj.AccountId == null) {
                conObj.addError('Account not Exist');
            }    
        }
    }
}


Trigger Handler:
 
trigger ContactTrigger on Contact (before insert,after insert) {
    if(Trigger.isAfter && Trigger.isInsert ) {
        ContactInsert.insertContact(Trigger.new);
    }
}



I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
Khan AnasKhan Anas (Salesforce Developers) 
Hi Aleem,

Greetings to you!

+1 Chetan

You can use below validation rule on Contact object:
ISBLANK( AccountId )

If you want to use trigger then below is the sample code:
trigger ContactError on Contact (before insert) {
    
    for(Contact con : trigger.new){
        if(con.AccountId==null){
            con.addError('Account should not be null');
        }
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas​​​​​​​