I'm running some validations and the validations are that: Every Employee should have two languages (English & Spanish) associated with it language type. (Lang_Type__c)
Otherwise user should not able to save the record and throw the validation errors, the below code works but not all the time, sometimes the validations pass even though the validation should failed. To give you an example, the user able to Save the record just by adding the English (should add both English/Spanish for that specific lang_type__c)
Lang_type__c = picklist (first language, home language)
So if I select lang_type__c = 'first language' or 'home language'
then I should have both Language__c = English and Spanish
Here is my code:
public static boolean ValidateLanguage(Id empId)
{
List<Emp_Languages__c> langList = [SELECT Id, Name, Language__c, Lang_Type__c FROM Emp_Languages__c WHERE Id =: empId];
map<string, boolean> mapLang = new map<string, boolean>();
for(Emp_Languages__c l : langList)
{
if(String.isNotEmpty(l.Lang_Type__c)) {
mapLang.put(l.Lang_Type__c, true);
}
else {
mapLang.put(l.Lang_Type__c, false);
}
}
boolean validationPass = true;
boolean hasEnSp = false;
String employeeLang = '';
boolean langEnglish = false;
boolean langSpanish = false;
for(Emp_Languages__c lang : langList)
{
hasEnSp = mapLang.get(lang.Lang_Type__c);
if(!hasEnSp )
{
employeeLang = '';
if(lang.Language__c == 'English')
{
employeeLang = 'English';
langEnglish = true;
}
if (lang.Language__c == 'Spanish')
{
employeeLang = 'Spanish';
langSpanish = true;
}
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'There should be two language English/Spanish');
ApexPages.addMessage(myMsg);
validationPass = false;
}
return validationPass && langEnglish && langSpanish ;
}
just to give you an sample data:
should validation fail:
Id Name Language__c Lang_Type__c
1 test English first language
2 abc Spanish home language
should validation pass:
Id Name Language__c Lang_Type__c
1 test English first language
2 abc Spanish first language