All,
I have seen this problem documented numerous times but have yet to find a fix that will address my situation. I am trying to either update an existing case or create a new on based on SOQL look up query results. It works if the case is existing but doesn't work and I get the below error in Workbench:
System.ListException: List index out of bounds: 0
I understand what the error means - no value returned. I want to create a new case based on this result. How do I fix this problem?
Here is my Apex class (look for extFormId for the problem):
@RestResource(urlMapping='/Cases/*')
global with sharing class CreateCases {
@HttpPut
global static ID upsertCase(String supplierId, String extUserId, String extFormId, String extFormType, String extFormName, String extUrl, String origin) {
System.debug('upsertCase Call');
list<RecordType> recordTypeName = new List<RecordType>([SELECT Id FROM RecordType WHERE SObjectType = 'Case' and Name = 'Connect']);
if(recordTypeName.size() >0) {
system.debug('recordTypeName : ' +RecordTypeName[0].Id);
}
list<Account> accountName = new List<Account>([select Id from account where organizer_id__c = :supplierID]);
if(accountName.size() >0) {
system.debug('accountName : ' +accountName[0].Id);
}
List<Contact> contactName = new List<Contact>([select Id from contact where organizer_user_id__c = :extUserId]);
if(contactName.size() >0) {
system.debug('contactName : ' +contactName[0].id);
}
System.debug('###1st extFormId : ' +extFormId);
list<Case> existingCase = new List<Case>([select Id from case where extform_id__c = :extFormId]);
If (existingCase.size() >0) {
system.debug('###2nd ExistingCase : ' +existingCase[0].id);
}
Case thisCase = new Case(
RecordTypeId = recordTypeName[0].Id,
AccountId = accountName[0].Id,
ContactId = contactName[0].Id,
extForm_ID__C = extFormId, // Need to use this field to determine existing or new case
Type = extFormType,
Subject = extFormName,
extURL__C = extUrl,
extUser_ID__c = extUserId,
Status = 'New',
Priority = 'Medium',
Origin = origin,
//Id = null);
Id = existingCase[0].id);
// Match case by Id, if present.
// Otherwise, create new case.
upsert thisCase;
// Return the case ID.
return thisCase.Id;
}
}
[0]
references in your debug statements that could throw this error. You need to be checking all of those query results for.size() > 0
and supplying sensible defaults. The ternary operator?:
is your friend.