Tuesday, August 7, 2012

Default a repeating pageBlockSection to closed

To default a Salesforce.com pageBlockSection to closed in a Visualforce page, you can use the Salesforce twistSection javascript function.

However this won't work if you have a pageBlockSection inside a repeat tag, because this solution requires a literal reference. So I used the magic of jQuery to call the function for each repeated pageBlockSection.

Example

For the page snippet below:

<apex:repeat value="{!thisList}" var="thisItem">
    <apex:pageBlockSection title="{!thisItem.Name}" id="thisPBS">

         Some text in here
    </apex:pageBlockSection>
</apex:repeat>

Add the following to the page:

<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />

<script>
$(document).ready(function() {
    $('img[id*="thisPBS"]').each(function() {
        twistSection(this);
    });
});
</script>


Explanation

The jquery function executes on page load, loops through all the images with a name ending in thisPBS, and calls the twistSection function to close them.

This works because the rendered page has the id you specified via Visualforce on the end of the rendered ids of the pageBlockSections in the repeat tag, i.e.

img_j_id0:wholeForm:thisPB:j_id127:0:thisPBS
img_j_id0:wholeForm:thisPB:j_id127:1:thisPBS
img_j_id0:wholeForm:thisPB:j_id127:2:thisPBS

No comments: