We have a Segment picklist field that separates our accounts by platinum, strategic, premium, ect. We want to have the parent account display the highest segment of all the child accounts which could be a mix of all five. I've already got a set of the parent account Ids and a list of all the child and parent accounts.
I have this method that is looping through them but I don't know how to figure out what child value is the highest without doing if statements in the right order.
Once I have the highest value I want to compare that with the parent, so if it's already equal I don't have to update it.
public static List<Account> updateParentAcc(Set<Id> accSet, List<Account> accList)
{
List<Account> accToUpdate = new List<Account>();
String a = 'P - Platinum';
String b = '1 - Strategic';
String c = '2 - Premium';
String d = '4 - Select';
String e = 'NC - Not Covered';
for(Id parentId : accSet)
{
String parentSegment;
String childSegment;
for(Account acc : accList)
{
if(acc.Id == parentId)
{
parentSegment = acc.Segment__c;
}
}
for(Account ac : accList)
{
if(ac.ParentId == parentId)
{
if(ac.Segment__c == a)
{
childSegment = a;
break;
}
if(ac.Segment__c == b)
{
childSegment = b;
break;
}
if(ac.Segment__c == c)
{
childSegment = c;
break;
}
if(ac.Segment__c == d)
{
childSegment = d;
break;
}
if(ac.Segment__c == e)
{
childSegment = e;
break;
}
}
}
if(parentSegment != childSegment)
{
Account accP = new Account();
accP.Id = parentId;
accP.Segment__c = childSegment;
accToUpdate.add(accP);
}
}
return accToUpdate;
}
I think I want to have a break because once I have the value I need I don't need to loop through the records to see the same value, but with this code it will not work if the second record is higher than the first.
Where am I going wrong?
Map<Id,ChildAccount[]> childAccountsbyParentAccountId
whereChildAccount
is a wrapper on Account that implementsComparable
. Then you can offload the sorting to the Comparable implementation