在学习501的课程中,发现如下一段代码
<apex:page controller="TestRerenderExtension">
<apex:form id="theForm">
<apex:pageBlock mode="edit" title="Review Edit" id="reviewBlock">
<apex:pageBlockSection columns="1">
<apex:pageBlockSectionItem >
<apex:outputLabel value="Recommend for Alternate Position?"/>
<apex:inputCheckbox value="{!showAltPosition}">
<apex:actionSupport event="onchange" rerender="theForm" status="showAltStatus" />
</apex:inputCheckbox>
</apex:pageBlockSectionItem>
<apex:actionStatus startText="(rendering position information...)" id="showAltStatus"/>
</apex:pageBlockSection>
<apex:pageBlockSection rendered="{!showAltPosition}" id="altPositionBlock" title="Select the Alternate Position" columns="1">
<h1>This is a block</h1>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
这里比较奇怪,实际上要刷新的是“altPositionBlock”,但是为什么不直接用“altPositionBlock”,而要用form呢?
自己把代码改了一下,确实是不好用。
一开始以为是checkbox的值没有穿到后台,但是实际发现确实是传了。
在网上查了一下,发现这种情况需要在需要rerender的Section外层要再包一层outputPanel,然后把rerender制定为对应的outputPanel,而且layout要设置成block。试过后果然好用。(不设置block,HTML中是span,设置成block,HTML中是Div)
<apex:page controller="TestRerenderExtension">
<apex:form id="theForm">
<apex:pageBlock mode="edit" title="Review Edit" id="reviewBlock">
<apex:pageBlockSection columns="1">
<apex:pageBlockSectionItem >
<apex:outputLabel value="Recommend for Alternate Position?"/>
<apex:inputCheckbox value="{!showAltPosition}">
<apex:actionSupport event="onchange" rerender="sectionOuter" status="showAltStatus" />
</apex:inputCheckbox>
</apex:pageBlockSectionItem>
<apex:actionStatus startText="(rendering position information...)" id="showAltStatus"/>
</apex:pageBlockSection>
<apex:outputPanel layout="block" id="sectionOuter">
<apex:pageBlockSection rendered="{!showAltPosition}" id="altPositionBlock" title="Select the Alternate Position" columns="1">
<h1>This is a block</h1>
</apex:pageBlockSection>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
那为什要包一层呢?
实际上是因为,页面加载的时候因为checkbox默认是false的,所以altPositionBlock并没有被加载,也就是HTML页面中没有一个叫altPositionBlock的element,于是JS是无法刷新它的,加一个一直存在的外包装,就OK了