Salesforce Asked by MAUForSalesforce on January 21, 2021
I have a custom object called "Revence__c" with fields "profit1__c" and "profit2__c". Another custom object called "Product__c" is the parent of "Revence__c"
If both profit1__c and profit2__c are same for more than one record, I need to display those records name. The below logic skips the first record information, when multiple occurences are there. For example, ‘Prod1′,’Prod2′,’Prod3’ has same profit1__c and profit2__c, it is currently displaying only ‘Prod2’ and ‘Prod3’ only
List<String> revList = new List<String>();
for(Revence__c rev : prodDescList)
{
if(rev.profit1__c!= null && rev.profit2__c!= null )
{
if(revList.contains(rev.profit1__c+rev.profit2__c))
{
errorstring += rev.Name+' has some errors<br/>';
errorstring +='Multiple occurences approval<br/>';
}
else
{
revList.add(pdl.profit1__c+pdl.profit2__c);
}
}
}
It does only display Prod2 and Prod3 because first contains will never have the Prod1 in it as it gets added in the else condition. What you need is having a map with rev.profit1__c+rev.profit2__c as keys and Reverence names as values as a list. So that way you can first populate the map and then check from there. Sample code for the logic:
//create a map to hold all possible keys
Map<String, List<String>> revMap = new Map<String, List<String>>();
for(Revence__c rev : prodDescList) {
if(rev.profit1__c != null && rev.profit2__c != null ) {
//initialize list with either existing values or create new list
List<String> values = revMap.get(rev.profit1__c+rev.profit2__c) != null ? revMap.get(rev.profit1__c+rev.profit2__c) : new List<String>();
values.add(rev.profit1__c+rev.profit2__c);
revMap.put(rev.profit1__c+rev.profit2__c, values);
}
}
for(String key : revMap.keySet()) {
if(revmap.get(key).size() > 1) { //if key returns multiple values then add error message
for(String dupValue : revmap.get(key)) {
errorstring += dupValue +' has some errors<br/>';
errorstring +='Multiple occurences approval<br/>';
}
}
}
If profit1__c
and profit2__c
are String fields (which they look like they are) then instead of only checking not equal to NULL
, I do recommend using String.isNotBlank()
as it also checks for empty string.
Correct answer by tugce on January 21, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP