1

hi I'm new to salesforce. I have a basic question hope you guys can help me. I'm doing "Display a SOQL query on a Visualforce page" but throughout all the information i found query have to build in a constructor. Here i have 2 question: 1 Why it have to use constructor? 2 if it possible not to use constructor instead i can build in a method i named it, if yes how to code it?

<apex:page controller="Prac1_controller">

        <p>this is the contactlist</p>
        <apex:pageBlockTable value="{!con}" var="item">
               <apex:column value="{!item.Name}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>

</apex:page>


public class Prac1_controller {
    public List<contact> con{get;set;}
    
    public  Prac1_controller() {
        con= [SELECT Name, Id FROM contact]; 
    }
}
1
  • 2
    Unless there's a really good reason (e.g. because you're maintaining old Visualforce pages as part of your role) I would recommend focusing on LWC rather than Visualforce. VF is two generations old and was designed to support Web 1.0 not Web 2.0.
    – Phil W
    May 17, 2021 at 7:44

1 Answer 1

0

It does not need to be performed in the constructor, but must have populated the "con" property before it is used in the page. Since you present the table unconditionally this leaves few options:

  1. from the constructor (either in the constructor or in a method called from the constructor).
  2. from the "get" method for the "con" property (either directly or in a method called from the "get" method). See the Apex properties documentation for details.
  3. using a page "action" (though this would actually be going against recommendations for what the action should do and may lead to issues). See the page documentation for details.
1
  • option 2 is my favorite
    – cropredy
    May 17, 2021 at 23:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .