Tuesday, September 13, 2011

Rerender using Action Support in Visualforce pages

There are many instances when it looks simple that a component needs to be displayed only when there is a specific value in a picklist.

We tend to use actionsupport and rerender for such cases where we use actionsupport for some event like onchange or onclick etc and rerender to a specific component.

But many times we find that the rerender is not working properly and we need to struggle around for getting it work.

So it is necessary to understand this when you are using rerender for a component that has rendered attribute

If the component has a rendered attribute then wrap it with outputPanel or pageBlockSection or any other component and rerender to this wrapped component rather than the component that is rendered.

A simple example :

You want to render a field reason lost only when the Opportunity stage is Closed Lost

 <apex:page standardController="Opportunity" sidebar="false">  
   <apex:sectionHeader title="Edit Opportunity" subtitle="{!opportunity.name}"/>  
   <apex:form >  
     <apex:pageBlock title="Edit Opportunity" mode="edit">  
       <apex:pageMessages />  
       <apex:pageBlockButtons >  
         <apex:commandButton value="Save" action="{!save}"/>  
         <apex:commandButton value="Cancel" action="{!cancel}"/>          
       <apex:actionRegion >  
         <apex:pageBlockSection title="Basic Information" columns="1">  
           <apex:inputField value="{!opportunity.name}"/>  
           <apex:pageBlockSectionItem >  
             <apex:outputLabel value="Stage"/>  
             <apex:outputPanel >  
               <apex:inputField value="{!opportunity.stageName}">  
                 <apex:actionSupport event="onchange" rerender="thePanel"  
               <apex:actionStatus startText="applying value..." id="status"/>  
           <apex:inputField value="{!opportunity.amount}"/>  
           <apex:inputField value="{!opportunity.closedate}"/>  
       <apex:outputPanel id=”thePanel”>        
          <apex:pageBlockSection title="Closed Lost Information" columns="1"  
                   rendered="{!opportunity.stageName == 'Closed Lost'}">  
         <apex:inputField value="{!opportunity.Reason_Lost__c}"/>  

refer this link from community actionSupport rerender problem for details.

Hope this will help you if you are struggling with action support rerender issues.

Also many times due to Output Panel, fields will be distorted:
Try using outputPanel inside pageBlockSection.
 <apex:pageBlockSectionItem >  
 <apex:outputpanel id="panel 1">  
 <apex:outputLabel value="LabelName" rendered="{!oppty.field== 'Other'}"/>  
  <apex:outputpanel id="panel 2">  
 <apex:inputfield value="{!field}" rendered="{!oppty.field == 'Other'}" />