1

I am trying to figure out how to add to this wrapper class.

public class Invoice {

public String Type;
public LineItem[] LineItems;


public class LineItem {
    public String ItemCode;
    public Decimal LineAmount;  //600

}


}

I can initiate the Invoice List easily with

  Invoice newInvoice = new Invoice();

Then I can add to that list:

  newInvoice.Type = 'Sample';

However, how the heck do I add the multiple line items in the sub list??? This was my guess, but it's wrong:

 newInvoice.LineItem[0].ItemCode = '1234';

1 Answer 1

4

You can create new instance of LineItem first like below since LineItem is a child class of Invoice so you have to use Invoice.LineItem to initialize the class

Invoice.LineItem  lineItem1 = new Invoice.LineItem();
lineItem1.ItemCode = 'item1';
lineItem1.LineAmount = 10;

Invoice.LineItem  lineItem2 = new Invoice.LineItem();
lineItem2.ItemCode = 'item2';
lineItem2.LineAmount = 20;

Invoice.LineItem  lineItem3 = new Invoice.LineItem();
lineItem3.ItemCode = 'item3';
lineItem3.LineAmount = 30;

After that create a new instance of Invoice class and after that add into its variables type and LineItem

Invoice newInvoice = new Invoice();
newInvoice.Type = 'Sample';

 newInvoice.LineItems.add(lineItem1 );
 newInvoice.LineItems.add(lineItem2 );
 newInvoice.LineItems.add(lineItem3 );

Updates

You have receive an error because newInvoice.LineItem is null at the starting point.

So before adding the item to the list you have initialize the like

 Invoice newInvoice = new Invoice();
 newInvoice.Type = 'Sample';
 newInvoice.LineItems = new List<Invoice.LineItem>();
 newInvoice.LineItem.add(lineItem1 );
 newInvoice.LineItem.add(lineItem2 );
 newInvoice.LineItem.add(lineItem3 );
2
  • Thanks for that was what I wanted. I found that I hit a null error when adding the line items so I added an empty line like follows before adding them (ugly I know, I don't know what the problem was though: Invoice.LineItem EmptyLine = new Invoice.LineItem (); newInvoice.LineItems = new Invoice.LineItem[]{EmptyLine}; Commented Oct 16, 2017 at 20:39
  • @DanielHowell check the updated answer
    – Ratan Paul
    Commented Oct 16, 2017 at 21:03

You must log in to answer this question.

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