Nick B
Nick B

Reputation: 715

How to grab a value from one managed bean and use it to set another managed bean's property on post back

Basically I want to be able to grab a value from one managed bean when the page loads, and then post back to another bean (with other values in the form) with that original value as well...

Here's part of what I have so far (this is all in a form and works...)

 <h:selectOneMenu id="categoryMenu" required="true"
                                         value="#{expense.categoryID}" label="Category" onchange="

                                                var value = myJQuery(this).val().toLowerCase();
                                                alert('You chose ' + value)">
                            <f:selectItem itemValue="0" itemLabel=""/>
                            <f:selectItem itemValue="1" itemLabel="Food"/>
                            <f:selectItem itemValue="2" itemLabel="Gas"/>
                            <f:selectItem itemValue="3" itemLabel="Clothing"/>
                            <f:selectItem itemValue="4" itemLabel="Recreation"/>
                            <f:selectItem itemValue="5" itemLabel="Other"/>

                        </h:selectOneMenu>
                        <h:message for="categoryMenu"/>
                        <h:outputLabel for="amount" value="Amount" styleClass="requiredLbl"/>
                        <h:inputText id="amount" value="#{expense.amount}" required="true" label="Amount"/>
                        <h:message for="amount"/>
                        <br/>
                        <p:commandButton id="btnSave" value="Save" action="#{expense.saveExpense}" ajax="false"/>
                    </h:panelGrid>

but I also want to include this value in the post back (doesn't have to be in a hidden form but you get my point)...

 <input type="hidden" value="#{loginController.userID}" id="hiddenCategory"/>

Any thoughts?

Upvotes: 1

Views: 1872

Answers (1)

BalusC
BalusC

Reputation: 1108537

One of the ways is to just pass it as a request parameter.

<p:commandButton id="btnSave" value="Save" action="#{expense.saveExpense}" ajax="false">
    <f:param name="userID" value="#{loginController.userID}" />
</p:commandButton>

If the #{expense} is request scoped, just set it as follows:

@ManagedProperty("#{param.userID}")
private Long userID; // +setter

However, you need to understand that the enduser has full control over this value. If this really represents the currently logged-in user, as the variable name suggests, then you should not be passing it around through a form submit.

Assuming that the #{loginController} is a session scoped bean, just inject it in #{expense} bean as follows:

@ManagedProperty("#{loginController}")
private LoginController loginController; // +setter

or

@ManagedProperty("#{loginController.userID}")
private Long userID; // +setter

Upvotes: 4

Related Questions