You can use below expression to fetch Custom Label in trigger
String labelForDisease = Label.Label_for_Disease_Condition
/*UserInfo.getUserId() will return the Id of the Current User executing the transaction*/
Map<Id, User> userMap = new Map<Id, User>([SELECT Id, LHJ__c, Opted_In_To_Cross_Jurisdiction_Sharing__c FROM User WHERE Id = :UserInfo.getUserId()]);
/*UserInfo.getUserRoleId() returns the context user's role ID.*/
**Map<Id, UserRole> userRoleMap = new Map<Id, UserRole>([SELECT Id, DeveloperName FROM UserRole WHERE Id = :UserInfo.getUserRoleId()]);**
Iterate on the Trigger.New
List and use if blocks to check conditions and inside the if blocks you may use addError('Error Message')
method to throw an error if the condition fails and the record will not update.
For Example:
trigger TriggerName on Object_Name__c (before insert, before update){ //Must be on Before Insert and before update events
Map<Id, User> userMap = new Map<Id, User>([SELECT Id, LHJ__c, Opted_In_To_Cross_Jurisdiction_Sharing__c FROM User WHERE Id = :UserInfo.getUserId()]);
Map<Id, UserRole> userRoleMap = new Map<Id, UserRole>([SELECT Id, DeveloperName FROM UserRole WHERE Id = :UserInfo.getUserRoleId()]);
String labelForDisease = = Label.Label_for_Disease_Condition;
for(Object_Name__c rec: Trigger.New){
if (!userMap.get(UserInfo.getUserId()).LHJ__c.contains(rec.CA_Local_Health_Jurisdiction__c)) {
rec.addError('Validation error Message');
}
if (record.LR_Disease_Condition__c != labelForDisease) {
rec.addError('LR Disease Condition is not correct');
}
}
}
Add more if blocks as per your validation rule.
Field__c
being a mulipicklist mean that you need a trigger instead of a validation rule? Moving to a trigger to do validation is generally a last resort (it's harder to find the source of a validation error when you useaddError()
in a trigger, the trigger needs unit tests, etc...).INCLUDES()
is a function that is specifically meant to work on multipicklists.Validation Rules
. As far as I know,INCLUDES
is supported in SOQL only. That said, how to write validation logic inApex Triggers
is fairly well documented, and this post shows a lack of research or any good faith effort to solve the problem by the OP.