How to collapse all apex:pageBlockSection inside apex:repeat in Salesforce?

1. Define the id attribute for apex:pageBlock.

2. Iterate using for loop based on the list size using JavaScript and use the below to collapse by default based on the array/list index. In the below, i refers to array/list index.


Sample Code:

Visualforce Page:
<apex:page controller="AccordionController">
<apex:pageBlock title="Accounts and related Contacts" tabStyle="Account" id="pb">
<apex:repeat value="{!listAccounts}" var="acc">
<apex:pageBlockSection collapsible="true" title="{!acc.Name}">
<apex:repeat value="{!acc.Contacts}" var="con">
{!con.FirstName} {!con.LastName}<br/>
<!-- Collapsing all the Page Block Sections by default -->
console.log( 'Account List Size ' + {!listAccounts.size} );
for ( let i = 0; i < {!listAccounts.size}; i++ ) {
Apex Class:
public with sharing class AccordionController {

public List < Account > listAccounts {get;set;}

public AccordionController() {

listAccounts = [ SELECT Id, Name, Industry, ( SELECT Id, FirstName, LastName, Email FROM Contacts ) FROM Account ORDER BY Name LIMIT 10 ];




18x Salesforce Certified, Lightning Champion, Technical Author. Blogger blogging in