I had a requirement earlier inwhich whenever I insert a task it always stamp current user's Business unit to Task Business Unit. below were the code that I had written on before insert trigger.
User u = [Select Id, Name, BU__c,Multiple_BU_User__c from User where Id = : UserInfo.getUserId()];
if (tasksForProcessing <> null) {
for (Task t: tasksForProcessing) {
if (String.isBlank(t.BU__c)) {
t.BU__c = u.BU__c;
}
}
}
Now our client has introduced an additional field called as Multiple BU.The purpose of this field is user may belongs to multiple BU(Earlier every users belongs to single BU).This field is of type checkbox.So when a user belongs to Multiple BU then this field checkbox is set to true. Now they want to put validation rule on task like when Multiple_BU_User__c=true and BU__c=blank then they want to throw the validation message here. Problem is as per salesforce order of execution,All Before Triggers execute first then validation rule. So when user belongs to multiple BU,it does not throw validation message for such users because I am assigning Business Unit Value on before insert event.
So I have tried to divide this code into 2 parts. Below code is for Single Business Unit User which is working as expected:
User u = [Select Id, Name, BU__c,Multiple_BU_User__c from User where Id = : UserInfo.getUserId() AND Multiple_BU_User__c=false];
if (tasksForProcessing <> null) {
for (Task t: tasksForProcessing) {
if (String.isBlank(t.BU__c)) {
t.BU__c = u.BU__c;
}
}
}
Below code is for Multiple Business Unit User which is not working as expected:
User usr = [Select Id, Name,BU__C,Multiple_BU_User__c from User where Id = :UserInfo.getUserId() AND Multiple_Business_Unit_User__c=true];
if (tasksForProcessing <> null) {
for (Task tsk: tasksForProcessing) {
if(String.isBlank(tsk.BU))
{
tsk.addError(Label.Task_Validation_Error);
}
else if(String.valueOf(tsk.Subject).contains(':')) {
system.debug('Contains :');
tsk.BU__c = usr.BU__c;
}
}
In this code I want to display validation message while creating task if user sets Business Unit value as blank that I have mentioned in IF block.
Problem comes when I am trying to create a task via Salesforce For Outlook(When we add any email to salesforce it stores in contact as a task),it does not allow me to create a task as it throws validation message.
As per salesforce order of execution this is valid because Before Trigger executes first then Validation Message.
In this case I am setting the Business Unit Value and at the same time I am checking validation message which creates a conflict in this case.
Instead of if(String.isBlank(tsk.BusinessUnit__c)) this perticular condition if I use another condition like if(String.valueOf(tsk.Subject).startsWith('Email:')) for SFO it will cause the problem when user is from differnt country(Local Value is other than English)
I want to know what is the best option that I can try in such situation?