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
Neal03416264103989518Neal03416264103989518 

How to handle the exception on a VF page when one of the Query does not return any result?

Hi,

I have a Visualfore page on which I need to conditionally render a commandlink. 

<apex:commandLink value="CrowdGuides" onclick="window.open('/apex/cGuide__Guide_Viewer?id={!CrowdGuideid}&url=https%3A%2F%2Fcs10.salesforce.com%2F001%2Fo','_blank','width=700,height=700');return False;"/>

I have added a Query in the controller class to get the CrowdGuideId
Private final id CrowdGuideid = [SELECT ID FROM cGuide__Guide__c WHERE (cGuide__Object_Prefix__c = '001' and cGuide__Active__c = true) order by cGuide__Likes__c desc limit 1].id;

The controller runs in WIth Sharing mode and some of our users does not have access to the records on the Guide__c object. Hence, when they try to open the VF page, system is throwing the exception. 

1. How can I handle the scenario, when the query did not return any result?
2. How can I render the commandlink only when the Query returned result?

Thank You for the help in Advance!!
Gonzalo AbrunaGonzalo Abruna

First, you have to use a List instead of a Id as a result of the query:

Private final id CrowdGuideid = null;
List<cGuide__Guide__c> lGuides = [SELECT ID FROM cGuide__Guide__c WHERE (cGuide__Object_Prefix__c = '001' and cGuide__Active__c = true) order by cGuide__Likes__c desc limit 1]; //If list is empty, you will not have an exception
if(lGuides != null && !lGuides.isEmpty()){
      CrowdGuideid = lGuides[0].Id;
}

Now, in your vf page you should have something like the following:
<apex:commandLink value="CrowdGuides" onclick="window.open('/apex/cGuide__Guide_Viewer?id={!CrowdGuideid}&url=https%3A%2F%2Fcs10.salesforce.com%2F001%2Fo','_blank','width=700,height=700');return False;" rendered="{!NOT(ISNULL(CrowdGuideid))}"/>

And you should have it.

Happy coding!