Visualforce Page:
Apex Controller:
public class AccountWithContactsController { public Id selectedAccountId { get; set; } public Listaccounts { get; set; } public List contacts { get; set; } public AccountWithContactsController() { accounts = [SELECT Id, Name FROM Account]; } public void showContacts() { contacts = [SELECT Name, Email, Phone FROM Contact WHERE AccountId = :selectedAccountId]; } }
In this example, the AccountWithContactsController retrieves a list of all Accounts and stores it in the accounts variable.
The showContacts method is called when the “Show Contacts” button is clicked, and it retrieves a list of Contacts related to the selected Account and stores it in the contacts variable. The reRender attribute on the command button tells Visualforce to redraw the section of the page with the ID “contactsSection” after the showContacts method is called, which will display the related Contacts.
Output:
Demo :