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
JR NonprofitJR Nonprofit 

Using SOQL to populate datatables in force.com

I am trying to populate a datatable (or pageblocktable) in force.com and can't seem to get the controller right.  I am using a custom controller and am trying to get opportunities to display in the table on my visual force page.  I think I have the table correct in my page code since I can get it to display correctly if I set up the soql code to retrieve only one row.  But if I need to display multiple rows, I can't seem to get the variable right.  I'm new at this and it seems that my variable set ups are not correct.
 
My code looks something like this:
 
public class MyController {
    
    Opportunity opportunity;
    
    
    public opportunity getOpenOpportunities(){
        for (opportunity: [select amount, closeDate, id, name, stagename from Opportunity where accountId=:ApexPages.currentPage().getparameters().get('accid') and isClosed=FALSE])
        {
        return opportunity;
        }
    }
This code returns an error indicating an invalid loop variable declaration.  Can anyone tell me how to fix this?
 
Thanks for your help.
 
werewolfwerewolf
You have to give the loop variable a type, like

for (Opportunity opp : [select fields from Opportunity])
JR NonprofitJR Nonprofit

When I try that, I get the following error:

Error: Compile Error: Non-void method might not return a value

Either the method or the variable seems to be set up wrong.

 

SuperfellSuperfell
if youre query returns no rows, there's no codepath that returns a value, which is needed.
werewolfwerewolf
Exactly.  You're telling Apex you're going to return an Opportunity:

public Opportunity getOpenOpportunities()

But then, if your query returns no values, it is possible that you will not ever in fact hit your return statement.  You may want to return NULL at the end of your statement.

That said, you are also setting yourself up for failure here anyway, because your method will only ever return the first row of the returned query, because you're returning it as soon as you loop through the results once.  If you want to return a list of open opportunities, your method should look more like:

public List<Opportunity> getOpenOpps()
{
    return [select amount, closeDate, id, name, stagename from Opportunity where accountId=:ApexPages.currentPage().getparameters().get('accid') and isClosed=FALSE];
}

JR NonprofitJR Nonprofit

This appears to have done the trick.

Thanks for your help.