+ Start a Discussion
Leo_VitaLeo_Vita 

Apex Sort order on Line Item numbers not working when trying 300: Code Custom App Logic tutorial

I am following the 300: Code Custom App Logic tutorial in the Force.com workbook, but after compiling the Apex Class and running the anonymous code. The result for the Line Item number order whithin an invoice remains the same.

 

The  anonymous code. is:

String s = InvoiceUtilities.renumberLineItems('INV-0004');

 

The apex Class is:

 

public class InvoiceUtilities {

    // class method to renumber Line Items for a given Invoice number
    // returns a string that indicates success or failure
    public static String renumberLineItems(String invoiceName) {

    // create a copy of the target Invoice object and it's Line Items
    Invoice__c invoice = [Select i.Name, (Select Name From Line_Items__r ORDER BY Name) 
                            From Invoice__c i 
                           Where i.Name = :invoiceName LIMIT 1];

    // loop through each Line Item, renumbering as you go
    Integer i = 1;
    for (Line_Item__c item : invoice.Line_Items__r) {
      item.Name = String.valueOf(i);
      System.debug(item.Name);
      i++;
    }

    // update the Line Items in one transaction, rollback if any problems
    // and return error messages to the calling environment
    try {
      database.update(invoice.Line_Items__r);
    }
    catch (DmlException e) {
      return e.getMessage();
    }

    // on success, return a message to the calling program
    return 'Line items renumbered successfully.'; 
  }
}

 

 

Can someone help me on this. Any help would be much appreciated.

Iqrar AhmedIqrar Ahmed
hi Leo_Vita,

This is because you are updating Line Item when you will insert new line item then order will be changed.

Regards