问题
I have a JSF 2.2 app with primefaces 4.0. I have a page with some checklboxes. What I want to acomplish is that when I click on one checkbox an ajax request to be fired to my managed bean. That request will hit a method that will return a string. So i do no need to update an element, but to get back the string in js, because if i achieve that then I can return an JSON.
I have this piece of code :
<p:selectManyCheckbox id="queues" value="#{viewAssignUsersMB.queueIds}" layout="grid" columns="3" converter="javax.faces.Long" converterMessage="Error.">
<f:selectItems value="#{viewAssignUsersMB.queues}"
var="queue"
itemValue="#{queue.id}"
itemLabel="#{queue.application.name}"/>
<p:ajax process="@this" partialSubmit="true" event="change" listener="#{viewAssignUsersMB.xxx()}" async="true" oncomplete="handleSaveRequest(xhr, status, args)"/>
and this method in backing bean :
public void xxx(){
RequestContext.getCurrentInstance().addCallbackParam("stringToBePassed","TriluLilu");
}
and my js callback method:
function handleSaveRequest(xhr, status, args) {
alert('User with username ' +args.stringToBePassed+ ' is saved successfully');
}
My main problem now is that I do not know how to detect what checkbox was last pressed as in my backing bean I have all the checked checkboxes (#{viewAssignUsersMB.queueIds})...
Is there a better approach for that, as this is a pretty common scenario/ What is the "classic" way to achieve that ... ?
回答1:
You can achieve this by using a remoteCommand.
- First: Hook
onchange
event on all the checkboxes inputs. - Second: In the event function handler, get the element value, and pass the value to the remoteCommand.
- Third: Read the value in the backing bean, as a request parameter.
xhtml
<p:selectCheckboxMenu id="selectCheckboxMenuId" widgetVar="selectCheckWV">
<f:selectItems value="#{mainBean.map}" />
</p:selectCheckboxMenu>
<p:remoteCommand name="submitNewCheckBoxValue"
process="@this selectCheckboxMenuId"
actionListener="#{mainBean.sendLastCheckedBox()}" />
javascript
<script>
$(document).ready(function() {
PF('selectCheckWV').inputs.change(function() {
if($(this).prop('checked'))
submitNewCheckBoxValue([{name: 'submitedValue', value: $(this).val()}]);
});
});
</script>
managedBean
public void sendLastCheckedBox() {
FacesContext facesContext = FacesContext.getCurrentInstance();
Map map = facesContext.getExternalContext().getRequestParameterMap();
String submitedValue = (String) map.get("submitedValue");
FacesMessage facesMessage = new FacesMessage(submitedValue);
facesContext.addMessage(null, facesMessage);
}
Here's a working Demo, and a small example on github [1][2]
Hope this helps.
来源:https://stackoverflow.com/questions/24165066/primefaces-pajax-return-value