3

I have a variable that successfully holds the result from a query in a trigger. I am able to use this variable to update the Contact record. However; if the query does not return records the variable is not assigned any value. I can't seem to test that the variable is blank and assign it a placeholder value.

How can I test the value of ExecEdCustomerSEMCODE when no records are returned and no value is assigned?

Thanks,

Kevin

// Most Recent Contact ExecEd SEM Code string ExecEdCustomerSEMCODE;

 ExecEdCustomerSEMCODE = [select SEM_Code__c from Interaction__c 
 WHERE Contact__c = :record.Contact__c AND SEM_Code__c != null 
 ORDER BY Start_Date_Time__c DESC LIMIT 1].SEM_Code__c;              

 if (String.isBlank(ExecEdCustomerSEMCODE)){
      ExecEdCustomerSEMCODE = 'test-blank';
      }

1 Answer 1

6

Here's you go:

List<SEM_Code__c> codes = [
    SELECT SEM_Code__c
    FROM Interaction__c
    WHERE Contact__c = :record.Contact__c
    AND SEM_Code__c != null 
    ORDER BY Start_Date_Time__c DESC
    LIMIT 1
];

String ExecEdCustomerSEMCODE;

//check the emptiness of the list this way before trying to pull the field off

if (codes.isEmpty()) {
    ExecEdCustomerSEMCODE = 'placeholdervalue';
else {
    ExecEdCustomerSEMCODE = codes[0].SEM_Code__c;
}
2
  • 2
    Using a ternary might have been a confuser in the answer, but here's a shorthand if you're familiar with it: String ExecEdCustomerSEMCODE = codes.isEmpty() ? 'placeholdervalue' : codes[0].SEM_Code__c; Commented Jan 8, 2014 at 19:20
  • the type of list and sObject being queried do not match in SOQL... Commented May 22, 2015 at 3:47

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.