Blog post

Display page block section collapsed on page load in Visualforce page

Posted on Apr 21, 2016
by Pradip Shukla
in Salesforce
with 0 comments

While your Visual force page development in Salesforce many of the developer got a requirement from their clients that they want this particular page block section collapsed on page load.

So to achieve this, let’s go one by one step.

I have created one VF page to display the list of contact in page block section. Here is my page and class code.

Class Code-

public class clsTwistSection 
{
    public list<Contact> lstCon{get;set;}
    
    public clsTwistSection()
    {
        lstCon = [select Id,Name,Email from Contact];
    }
}

Page Code -

<apex:page controller="clsTwistSection" tabStyle="Contact" id="idPage">
  <apex:sectionHeader title="All" subtitle="Contact Records"/>
  <apex:form id="idForm">
      <apex:pageBlock id="pgBlock">
          <apex:pageBlockSection title="Contact Records" columns="1" id="idPBS">
              <apex:pageBlockTable value="{!lstCon}" var="x">
                  <apex:column value="{!x.Name}"/>
                  <apex:column value="{!x.Email}"/>
              </apex:pageBlockTable>
          </apex:pageBlockSection>
      </apex:pageBlock>
  </apex:form>
</apex:page>

Now your page will look like below-(in this you can see that your page block section is open when page loads.


And your client is asking something like below screen

As we know that when page block section rendered as HTML then we can see below html code. And to get that code just right click on your page block section and you will see that, and in my case here it is-

So to achieve your requirement, put below line code just after page block section tag in your page code

<script> twistSection(document.getElementById("idPage:idForm:pgBlock:idPBS").getElementsByTagName("img")[0]) </script>

And after putting above line your VF page code looks like 

<apex:page controller="clsTwistSection" tabStyle="Contact" id="idPage">
  <apex:sectionHeader title="All" subtitle="Contact Records"/>
  <apex:form id="idForm">
      <apex:pageBlock id="pgBlock">
          <apex:pageBlockSection title="Contact Records" columns="1" id="idPBS">
              
<script> twistSection(document.getElementById("idPage:idForm:pgBlock:idPBS").getElementsByTagName("img")[0]) </script>
              <apex:pageBlockTable value="{!lstCon}" var="x">
                  <apex:column value="{!x.Name}"/>
                  <apex:column value="{!x.Email}"/>
              </apex:pageBlockTable>
          </apex:pageBlockSection>
      </apex:pageBlock>
  </apex:form>
</apex:page>

So when you save the changes you just made, you will get the required output on page load.

Happy Coding!!!

 


0

Leave your comment

Leave your comment