+ Start a Discussion
Thomas KorthuisThomas Korthuis 

Concatenate string in child/related records for Order / OrderItem relationship

I'm fairly new to writing out apex code, so any input would be greatly appreciated. 

Here is the current setup and problem I'm running into:
I have a custom formula field with the OrderItem Object which generates a JSON string based on the product information (this JSON string is used to send lineItem order information to another system). This field is called QBO_Line_JSON__c. I'm trying to populate a custom field in the Order object (QBO_JSON__c) that combines all the QBO_Line_JSON__c fields from the related OrderItem records. The goal is to have one JSON string that can be queried from the external system that lives in the Order object.

Here is the code so far:
trigger qboJSONCreator on Order (after insert, after update, after delete, after undelete) {

List<Order> OrderList = (Trigger.isInsert|| Trigger.isUnDelete) ? Trigger.new : Trigger.old;

List<Id>OrderIds = new List<Id>();

for (Order OrderStr : OrderList) {
OrderIds.add(OrderStr.OrderItems);
}

List<OrderItem> OrderItemList = [select id, (select id, QBO_Line_JSON__c from OrderItems) from Order where id in :OrderIds];

for (OrderItem ordr :OrderItemList) {
  for(integer i=1;i < ordr.OrderItem.size();i++)
  {
    ordr.QBO_JSON__c = ordr.QBO_JSON__c + '; ' + string.valueOf(ordr.OrderItem[i].QBO_Line_JSON__c);
  }
}

update OrderItemList;

}
The above gives me an error "Incompatible element type List<OrderItem> for collection of Id"

I've looked but haven't been able to piece together an understanding of how to resolve it. 

Any input or pointing in the right direction would be great. 

Thanks in advance!

 
Jim JamJim Jam
Change line 8 to OrderIds.add(OrderStr.Id);
Thomas KorthuisThomas Korthuis
Thank you Jim Jam! That resolved the error :)

It did produce another one: "Illegal assignment from List<Order> to List<OrderItem>"  doing some searches on resolving that one now. 

Thanks so much!
Jim JamJim Jam
Line 11 should be List<Order> OrderItemList....

and then Line 13 should be for (Order ordr :OrderItemLIst) ....
Thomas KorthuisThomas Korthuis
That is awesome! Working :) :) (with one more adaptation).

Final Code:
 
trigger qboJSONCreator on Order (after insert, after update, after delete, after undelete) {

List<Order> OrderList = (Trigger.isInsert|| Trigger.isUnDelete) ? Trigger.new : Trigger.old;

List<Id> OrderIds = new List<Id>();

for (Order OrderStr : OrderList) {
OrderIds.add(OrderStr.Id);
}

List<Order> OrderItemList = [select id, (select id, QBO_Line_JSON__c from OrderItems) from Order where id in :OrderIds];

for (Order ordr :OrderItemList) {
  for(integer i=1;i < ordr.OrderItems.size();i++)
  {
    ordr.QBO_JSON__c = ordr.QBO_JSON__c + ', ' + string.valueOf(ordr.OrderItems[i].QBO_Line_JSON__c);
  }
}

update OrderItemList;

}

Change was in line 14 and 16: OrderItem was changed to OrderItems

Jim Jam, thanks again.