Sunday, May 18, 2014

How to Collapse the Apex Page block Panel on page load

If you have a big page with a lot of fields and multiple sections on the form, then you might want to collapse some of the sections on the form on page load. Although salesforce does not provide any thing out of the box to have those sections as collapsed by default but we can write a quick javascript hack to do this. 

Salesforce has a function twistSection which gets fired on click of the image to collapse or expand the page block section. So all we need to do is to pass the image object to this function and it toggles the section. On page load the sections are always expanded hence just by calling this function on page load will ensure that the section is collapsed after the page load. 

Here is the code to collapse a section on page load. 

Suppose the panel code is as given below 

<apex:pageBlockSection collapsible="true" title="MD" id="MDsection">

Then first we need to get the panel element by id using the code 

var mdsec = document.getElementById('{!$Component.MDsection}');

You might have to use form name and page block name based on where you put the  java script code in the page.

After this on page load you need to write the following code

twistSection(mdsec.childNodes[0].childNodes[0]);

This will ensure that the page block section will be collapsed on the page load.