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
Kumar DavidKumar David 

Trigger to prevent creating task if Account Type is Bill to Customers

I need to put validation on Task so that Task cannot be created for Accounts other than "Sold to Customer" and "Prospect Customer". Currently Task can be created even for "Bill to Customer". There is no option to create a validation rule with task hence I need to have Before insert and before update Trigger. (Type is a picklist in Account that has value: Sold to Customer, Prospect Customer, Bill to Customer)

trigger TaskCanbeCreatedforSoldtoOnly on Task (before insert, before update) {
    for (Task t: Trigger.new){
         if(t.Account.Type== 'Bill To Customer') {
                     t.addError ('Please select the Sold to Customer');
        }
    }
}

Thank you
Best Answer chosen by Kumar David
@anilbathula@@anilbathula@
Hi Kumar,

Try this code:-
trigger TaskCanbeCreatedforSoldtoOnly  on Task (before insert, before update) {

set<id>accids=new set<id>();

for(task t:trigger.new){
    accids.add(t.whatid);
}
if(!accids.isempty()){
    List<Account>lstacc=[select id,Type from account where id in:accids AND Type=:'Bill To Customer'];
    Map<id,String>mapofaccts=new Map<id,string>();
    for(account acc:lstacc){
        mapofaccts.put(acc.id,acc.Type);
    }
    for(task t:trigger.new){
        if(mapofaccts.containsKey(t.whatid)){
            t.addError ('Please select the Sold to Customer');
        }
    }
}

}

There might be some typo errors please check once.

Thanks
Anil.B​​​​​​​

All Answers

@anilbathula@@anilbathula@
Hi Kumar,

Try this code:-
trigger TaskCanbeCreatedforSoldtoOnly  on Task (before insert, before update) {

set<id>accids=new set<id>();

for(task t:trigger.new){
    accids.add(t.whatid);
}
if(!accids.isempty()){
    List<Account>lstacc=[select id,Type from account where id in:accids AND Type=:'Bill To Customer'];
    Map<id,String>mapofaccts=new Map<id,string>();
    for(account acc:lstacc){
        mapofaccts.put(acc.id,acc.Type);
    }
    for(task t:trigger.new){
        if(mapofaccts.containsKey(t.whatid)){
            t.addError ('Please select the Sold to Customer');
        }
    }
}

}

There might be some typo errors please check once.

Thanks
Anil.B​​​​​​​
This was selected as the best answer
Kumar DavidKumar David
Hi Anil,

Very impressed, not even typo error. It worked like a charm. I believe we need test class for this right? Will be provide me some guidance for writing a test class. Thank you
Kumar DavidKumar David
Hi Anil,

Thank you for your suggestion.