Search code examples
salesforceapex-code

Accessing data from Apex


First, I'm just a rookie and it's my 3rd day work. I created a object called

  • Merchandise

    a page and wrote a class to control the page, below are some details of them

1.The Page

<apex:dataTable border="1px" value="{!searchResults}" var="pitem" rowClasses="odd,even">
          <apex:column headerValue="Product" width="100">
              <apex:outputText value="{!pitem.name}"></apex:outputText>
          </apex:column>
          <apex:column headerValue="  Price" width="70">
              <apex:outputText value="{!pitem.Price__c}"></apex:outputText>
          </apex:column>
          <apex:column headerValue="Unit Price" width="200">
              <apex:outputtext value="{!pitem.Unit_Price__c}"></apex:outputText>
          </apex:column>
          <apex:column headerValue="Unit Price" width="200">
              <apex:outputtext value="{! IF(pitem.Price__c > 15, 'Unit Price is normal','Unit Price is too low')}"></apex:outputText>
          </apex:column>
     </apex:dataTable>  

2.Class

public class Bo_Test{
    public static integer age = 20;
    public string city{get; set;}
    public string name{get; set;}
    public static List<Merchandise__c> searchResults {get;set;}
    
   public Bo_Test(){
    searchResults = new List<Merchandise__c>();
    String queryString = 'SELECT Price__c, Name, Unit_Price__c from Merchandise__c';
    searchResults = Database.query(queryString);
    //this.city = "Jersey City";
    //name  = "Bobo";   
}
    


    public PageReference sayHello(){
        return null;
    } 
}

In the page display, there are no data showed from the Merchandise object(actually there are a lot), did I do it wrong way? how to access the data by editing the apex class?

The point is, Until now I still have no ideas about the page and class related to each other, does it call the default constructor? any kind of suggestions are welcomed!!

Help me! I'm looking forward hearing from you guys


Solution

  • First and foremost, are you binding the page to Bo_Test controller ?

    <apex:page controller="Bo_Test"> 
       <apex:dataTable .......
    

    If that is not your problem, try changing your class by

    public class Bo_Test{
        public List<Merchandise__c> searchResults {get;set;}
    
        public Bo_Test(){
            searchResults = [SELECT Price__c, Name, Unit_Price__c from Merchandise__c];
        }
     }
    

    Notice that I've removed the static property to searchResults.

    In addition this initialization is not need.

    searchResults = new List<Merchandise__c>();