0

Does anybody see what is the mistake in this snippet of code?

List <AccountHistory> accHistory = [SELECT Id, Account.name, Field, OldValue, NewValue 
                                    FROM AccountHistory                                                                                                                              
                                    WHERE AccountId = 'asada978asd'                                                                                                                                  
                                    AND field ='Primary_Phone__c'];

List<AccountHistory> accHistList = new List<AccountHistory>();

if(accHistory.size() > 0) {
   for( AccountHistory accHis : accHistory){
      accHistList.add(accHis[0].NewValue);          
   }
}

When I try to run it I get this error:

"compileProblem": "Expression must be a list type: AccountHistory",
  "compiled": "false",
  "exceptionMessage": "",
  "exceptionStackTrace": "",

What I am trying to do here is I try to grab all values of phone that were changing through the history, put them into list, sort that list and then to be able to say "Ok I want to grab only last and before last value".

1 Answer 1

2

In this fragment...

for( AccountHistory accHis : accHistory){
   accHistList.add(accHis[0].NewValue);          
}

accHis is a single instance of AccountHistory, so you can't use the array index notation there.

Additionally, since accHistList is a List<AccountHistory>, trying to add a string (accHis.newValue) to it would also generate an error.

If you're simply looking to add data to a list, there's no need for a loop. secondList.addAll(firstList); is all you really need (provided the lists are of compatibble types).

If you really are looking to extract a field value from each record, then a loop is necessary. You'd need to change the list type of accHistList to be something appropriate (like List<String>), and the check for accHistory.size() > 0 is not required.

1
  • Great, thanks for your answer. It works now and this is how my code looks now. I applied changes per your suggestion and this is how it looks like now: List<String> accHistList = new List<String>(); for(AccountHistory accHis : accHistory){ accHistList.add((String)accHis.NewValue); }
    – mhdev
    Commented Feb 10, 2022 at 17:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .