1

I have an apex method that requires three fields, an account number, user input and custom setting number. based on that it will generate a sequence of number
e.g if the acccount no is 8181818 (OpenReach) userinput is 3 and the custom setting number is 1112 . it will generate
1113 Openreach
1114 OpenReach
1115 OpenReach

But it the account number doesn't correspond with an account it will come up with

1113
1114
1115

I already put an required field on the form that handles an empty field. But I can't figure out how to display an error message so that it shows and stops the code from going any further.
Here is what I tried to do:

public void genumber(){

         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;
    } else { ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Warning, 'The account number is invalid')); }


         mapUserInputToLargeNo = new map<Integer, Decimal>();
         do{


        if(cslist.size() >0)
        largeNum = cslist[0].Largest_Number__c;
        largeNum ++;

        for (Number_Setting__c updt : cslist){
            updt.Largest_Number__c = largeNum; 
            update updt; 

        }  

         mapUserInputToLargeNo.put(userinput, largeNum);
         userinput --;

      } while(userinput >  0);
   }

I've also tried to do the error handling and do it other way around:

      if (lstAccount.IsEmpty()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Warning, 'The account number is invalid'));
         system.debug('no accounts found');
     }
        else{system.debug('Found account name ');}

Has anyone got any idea ? I want a red error message popping out "Account doesn't exist" and stop the execution.

  • You should add a <apex:messages/> tag to the visualforce page. It will display all ApexPages... messages on the page. – Sergej Utko Mar 21 '16 at 9:25
  • But it will still generate the numbers without the account name – Greg Mar 21 '16 at 9:26
6

To display a message on your page you can add <apex:messages/> as suggested in the comments. And to stop execution you need to put the code that you don't want to execute if Account was not found inside your if(lstAccount.size() > 0){ ... } block. You can also add a return statement like that:

if(lstAccount.size() > 0){
     AccName = lstAccount[0].Name;
} else { 
     ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Warning, 'The account number is invalid'));  
     return;
}

That will stop your method execution after the return statement.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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