function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
LauraBTNLauraBTN 

Workshop 201, Tutorial 3, Step 4.3, Apex throwing error

I was following along in the Workbook successfully until I got to Workshop 201, Tutorial 3, Step 4.3,- I have checked and checked and do not see what I have done wrong.

Here is the code from the tutorial:
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.';
}
}
It saved with no errors

Then I test it using this :
String s = InvoiceUtilities.renumberLineItems('INV-0004'); 

My inv-004 is correct (has line numbers out of sequence.

Here is the error I keep getting:
System.QueryException: List has no rows for assignment to SObject: Class.InvoiceUtilities.renumberLineItems: line 8, column 1
AnonymousBlock: line 1, column 1
AnonymousBlock: line 1, column 1

Can anyone help with this?  

Thanks
Ashish_SFDCAshish_SFDC
Hi Laura, 


This issue has been addressed as below, 

The error is being thrown because your SOQL query isn't returning any values. SOQL always returns a list of objects and it will only properly be assigned to a single variable if only exactly one is returned. If a SOQL query results in zero results or more than one result, your queries will fail. You have to use List instead.

Replace 

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];


With 

List<Invoice__c> invoices = [SELECT i.Name,
                                                (SELECT Name
                                                 FROM Line_items__r
                                                 ORDER BY Name)
                                        FROM Invoice__c i
                                        WHERE i.Name = :invoiceName LIMIT 1];

http://stackoverflow.com/questions/21507860/getting-an-error-when-tried-to-execute-workbook-apex-code


Regards,
Ashish