Java – JSF (and PrimeFaces) How to pass parameter to a method in 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"
     <p:ajax event="valueChange" listener="#{employeeController.onValueChangedStart}"/>

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.

Best Solution

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();
// ...

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();
// ...

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.