1

As per my requirement,I need to check whether phone field of account object is null before inserting contact.If it is null,I should not allow user to create contact.I created trigger for this scenario,but unable to achieve functionality .I am posting my trigger code:

trigger CheckAcctPhoneBlank on Contact (Before insert) {

    for(Contact con:[Select id,account.phone,account.name from Contact where id in:trigger.new]){ 
        system.debug('Contact size**'+con);   
        system.debug('??test2??');
        system.debug('Phone details**'+con.account.phone);
        if(con.account.phone == null){
            con.addError('Contact cannot be inserted');
        }
    }
}
1
2

In a "before insert" trigger, there's no record to query (Id is null). You can change this to an after-insert trigger, or you can use a validation rule.

Alternatively, you can query the accounts first, then check:

Map<Id, Account> accounts = new Map<Id, Account>();
for(Contact record: Trigger.new) {
  accounts.put(record.AccountId, null);
}
accounts.putAll([SELECT Phone FROM Account WHERE Id = :accounts.keySet()]);
for(Contact record: Trigger.new) {
  if(accounts.get(record.AccountId) == null ||
     accounts.get(record.AccountId).Phone == null) {
    record.addError('Contact cannot be inserted');
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.