huahsin68
huahsin68

Reputation: 6979

How to update the property member variable of a managed bean?

I have a member variable in a managed bean, and this member variable is tied to the component in XHTML with a getter and setter. If I set the member variable in a function call, when the getter of this member variable is trigger, this member variable will still hold the old value. May I know how could I update this member variable so that the component could get the latest updated value?

The manage bean:

@ManagedBean(name = "myBean")
@SessionScoped    
public class MyBean {
  public boolean show = false;

  /** getter and setter **/

  public void theFunc() {
     this.show = true;
  }
}

XHTML code

<h:panelGroup id="Panel_1" rendered="#{myBean.show == true}">
   ...
   Some rubbish here
   ...
</h:panelGroup>

<h:panelGroup id="Panel_2">
   <h:commandLink action="#{myBean.doFunc}">
      <f:ajax event="action" render="Panel_1"/>
      <h:outputText value="XX" />
   </h:commandLink>
</h:panelGroup>

From this sample, the show variable is showing false even though theFunc() has already set to true.

Update on 06 Oct 2012 I have remove commandButton and replace with commandLink, I think it should be fine in term of usage.

Upvotes: 0

Views: 2326

Answers (2)

Kerem Baydoğan
Kerem Baydoğan

Reputation: 10722

Change your methods return type and name if you want it to be invoked.

Change this

  public void theFunc() {
     this.show = true;
  }

to this

  public String doFunc() {
     this.show = true;
     return null;
  }

otherwise this action can not work.

   <h:commandLink action="#{myBean.doFunc}">

then update parent of your panel like this

<h:panelGroup id="parentPanelGroupId">

    <h:panelGroup id="Panel_1" rendered="#{myBean.show}">
        ...
        Some rubbish here
        ...
    </h:panelGroup>

</h:panelGroup>

<h:panelGroup id="Panel_2">
   <h:commandLink action="#{myBean.doFunc}">
      <f:ajax render="parentPanelGroupId"/>
      <h:outputText value="SHOW/HIDE PANEL 1" />
   </h:commandLink>
</h:panelGroup>

NOTE:

use

rendered="#{myBean.show}"

instead of

rendered="#{myBean.show == true}"

Upvotes: 1

Mr.J4mes
Mr.J4mes

Reputation: 9266

Try this way:

<h:panelGroup id="toUpdate">

    <h:panelGroup id="Panel_1" rendered="#{myBean.show}">
        ...
    </h:panelGroup>

</h:panelGroup>

<h:commandButton action="#{theBean.doCalculation}">
    <f:ajax render="toUpdate" />
</h:commandButton>

There are 2 things to note:

  1. You need to wrap <h:panelGroup id="Panel_1"> inside another <h:panelGroup> or something eles which is always rendered. Otherwise, if the show variable is initially false, the ajax update may not work since JSF renderer cannot find the the component with id="Panel_1" when you use <f:ajax render="Panel_1" />.
  2. rendered="#{myBean.show}" is good enough :P. Since show is a boolean variable, you don't need rendered="#{myBean.show == true}".

Upvotes: 1

Related Questions