2

I want to add an apex message inside of my method that will showup if query returns a null value. Here is a bit of the code that includes query.

AccName = [Select Name, Customer_Account_Number__c 
             from Account where Customer_Account_Number__c =:uano limit 1].Name;

    if (AccName == Null) {
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Warning, ''));
                system.debug('Empty string');
     }
     else{system.debug('found acc name ');}

unfortunately when a user types in a wrong number an error message in a salesforce pages shows up and I'm trying to avoid that. What could a best solution for that be ?

enter image description here

4

Its always advisable to assign the query to a list and do the processing from the list.

So change this

AccName = [Select Name, Customer_Account_Number__c 
         from Account where Customer_Account_Number__c =:uano limit 1].Name;

to

List<Account> lstAccount = [Select Name, Customer_Account_Number__c 
         from Account where Customer_Account_Number__c =:uano limit 1];
if(lstAccount.size() > 0)
    AccName = lstAccount[0].Name;
3

The correct way to query for a record you aren't sure exists is to pull it down as a list:

List<Account> candidates = [/*query*/];
accName = !candidates.isEmpty() ? '' : candidates[0].Name;
  • Per OP context, accName is a String. So candidates[0].Name should be assigned to it. – Vigneshwaran G Mar 17 '16 at 14:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.