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

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.
twistSection(document.getElementById(‘{!$Component.pb}’).getElementsByTagName(‘img’)[i]);
 
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:pageBlockSectionItem>
                    <apex:repeat value=”{!acc.Contacts}” var=”con”>
                        {!con.FirstName} {!con.LastName}<br/>
                    </apex:repeat>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:repeat>
        <!– Collapsing all the Page Block Sections by default –>
        <script>
            console.log( ‘Account List Size ‘ + {!listAccounts.size} );
            for ( let i = 0; i < {!listAccounts.size}; i++ ) {
                twistSection(document.getElementById(‘{!$Component.pb}’).getElementsByTagName(‘img’)[i]);
            }
        </script>

    </apex:pageBlock>
</apex:page>

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 ];
        
    }
    
}

 
Output:
 
 

Leave a Reply