JSF(和PrimeFaces)如何将参数传递给ManagedBean中的方法 [英] JSF (and PrimeFaces) How to pass parameter to a method in ManagedBean

查看:163
本文介绍了JSF(和PrimeFaces)如何将参数传递给ManagedBean中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在输入文本中显示了一个Employee对象. 例如,雇员的名字显示在输入文本中.当这个名字的值改变时,它会调用一个方法.在完成此操作之前,我想调用一个将员工ID保存在ManagedBean中的方法,这样我就知道需要更改哪个员工. 到目前为止,我该怎么做:

I have an Employee object I am showing in inputtext. For example, the firstname of the employee is shown in an inputtext. When the value of this firstname changes it calls a method. Before this is done I want to call a method which saves the ID of the employee in the managedbean so I know which employee needs to be changed. How do I do this, I got this so far:

<h:outputText value="First name:"/>
<p:inplace id="firstname" editor="true">
     <p:ajax event="save" onsuccess="#{employeeController.saveName()}"/>
     <p:inputText id="firstName" value="#{emp.firstName}"  
                  required="true" label="text"
                  valueChangeListener="#{employeeController.firstNameChanged}">
     <p:ajax event="valueChange" listener="#{employeeController.onValueChangedStart}"/>
     </p:inputText>
</p:inplace>

我想我应该使用onValueChangedStart或firstNameChanged方法传递ID.我该怎么做呢?还是有更好的方法来做到这一点? emp有一个吸气剂.所以#{emp} .id可以得到它.

I guess I should pass the ID with the onValueChangedStart or firstNameChanged method. How do I do this? Or is there a better way to do this? There is a getter for the emp. So #{emp}.id to get it.

推荐答案

假设您确实在一个重复的组件中,而#{emp}通过其var属性公开,则可以从EL范围中获取它.在值更改侦听器中,如下所示:

Assuming that you're indeed inside a repeating component where #{emp} is been exposed by its var attribute, you could just grab it from the EL scope inside the value change listener as follows:

FacesContext context = FacesContext.getCurrentInstance();
Employee employee = context.getApplication().evaluateExpressionGet(context, "#{emp}", Employee.class);
Long id = employee.getId();
// ...

或者,如果将<h:dataTable>value包裹在DataModel<Employee>内,则可以按如下方式获取当前行:

Alternatively, if you wrap the value of the <h:dataTable> inside a DataModel<Employee>, then you can obtain the current row as follows:

Employee employee = model.getRowData();
Long id = employee.getId();
// ...

无关与具体问题无关,不必为值更改设置两个侦听器方法.请注意,valueChangeListener使您有机会通过事件获取旧值和新值,而p:ajax listener则没有,因为此时新值已被设置为模型值.如果同时需要旧值和新值,请删除<p:ajax>listener属性.顺便说一下,event="valueChange"已经是默认事件,所以也将其删除.

Unrelated to the concrete problem, it's unnecessary to have two listener methods for the value change. Note that the valueChangeListener gives you the opportunity to get both the old and new value by the event and the p:ajax listener not, the new value is already been set as model value at that point. If you need both the old and new value, remove the listener attribute of <p:ajax>. The event="valueChange" is by the way the default event already, so just remove it as well.

这篇关于JSF(和PrimeFaces)如何将参数传递给ManagedBean中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆