Catch KeyCode in AjaxBehaviorEvent of JSF 2 - java

I have a JSF ajax keyup event linked to an event listner in a backing bean.
The code in the JSF file is like below.
<h:inputText id="txtDescription" value="#{institutionController.current.description}" disabled="#{institutionController.modifyControlDisable}" >
<f:ajax event="keyup" listener="#{institutionController.changeDetailsEvent}" />
</h:inputText>
The code in the backing bean is like below.
public void changeDetailsEvent(AjaxBehaviorEvent event) {
}
I want to achieve different logic depending on the key presses, like shown is pseudocode below.
public void changeDetailsEvent(AjaxBehaviorEvent event) {
If (event.key = Key.enter) {
do something;
} else if (event.key = Key.Escape) {
so something else;
} else {
do nothing;
}
}
Can someone please tell me how this is done in the backing bean?

The AjaxBehaviorEvent doesn't contain any information about the JavaScript event object. You need to pass the desired information along yourself. This can be achieved by a hidden input field whose value is to be prefilled by JavaScript. For example,
<h:inputText value="#{bean.input}" onkeyup="document.getElementById('#{keyCode.clientId}').value=event.keyCode">
<f:ajax event="keyup" execute="#this keyCode" listener="#{bean.listener}" />
</h:inputText>
<h:inputHidden id="keyCode" binding="#{keyCode}" value="#{bean.keyCode}" />
(please note that the id of the hidden field is included in execute so that it get submitted along on the ajax request, please also note that the binding is used to be able to dynamically obtain the generated client ID in document.getElementById() in order to set the key code value, you could alternatively also hardcode the client ID if it's fixed)
with
private String input;
private int keyCode;
public void listener() {
switch (keyCode) {
case 13:
// Enter key was pressed.
break;
case 27:
// Escape key was pressed.
break;
default:
// Other key was pressed.
break;
}
}
You can find an overview of all valid keyCode values in the Mozilla DOM reference.

Related

Default value for <tr:selectOneRadio> if the value is from database object

I am struggling with this for a really long time. I am changing code and I need to put default value to selectOneRadio element from Trinidad. I have object from database (for example called result). This object has attribute decision. In the select element value parameter was used this way value="#{result.decision}".
Now I need If result.decision is empty set value to True. If value is False let/set value to False. And if value is True let/set value to True. I tried something like this in template:
<tr:selectOneRadio id="decision" value="#{viewBean.changeValueToOne(result)}" autoSubmit="true" immediate="true">
<f:selectItem itemValue="true" itemLabel="Yes"/>
<f:selectItem itemValue="false" itemLabel="No"/>
</tr:selectOneRadio>
And this function in viewBean:
public Boolean changeValueToOne(ResultDTO result) {
if (result.getDecision() == null) {
result.setDecision(Boolean.TRUE);
}
return result.getDecision();
}
But when I did this I got only one String value instead of selectOneRadio element. There was only "Yes" or "No" value.
How can I set default value to selectOneRadio element to the value from the object and get a normal selectOneRadio, not just one value.
EDIT
This is code from template. Decision is the object from the database where I need to change value:
<tr:selectOneRadio id="decisionYes" value="#{viewBean.defaultDecision}" valueChangeListener="#{viewBean.valueChangedOneRadioListener(decision)}"
autoSubmit="true" immediate="true">
<f:selectItems value="#viewBean.decisionStates}"/>
</tr:selectOneRadio>
This is a listener method from viewBean:
public void valueChangedOneRadioListener(DecisionDTO decision, ValueChangeEvent event)
{
if(event.getNewValue() != null) {
if((Boolean)event.getNewValue().equals(Boolean.TRUE))
{
decision.setDecision(Boolean.TRUE);
} else {
decision.setDecision(Boolean.FALSE);
}
// this is variable used in selectRadio
this.setDefaultVyjadreni((Boolean)event.getNewValue());
}
}
When I run this code I got error because method wasn't found.
javax.faces.event.AbortProcessingException: Method valueChangedOneRadioListener not found
I use integer Values for the Trinidads selectOneRadio.
You set the default by setting yourValue.
You react on a change event with a valueChangeListener.
<tr:selectOneRadio
id="maschineId"
value="#{yourBean.yourIntValue}"
valueChangeListener="#{yourValueChangeListener}"
autoSubmit="true">
<f:selectItem itemValue="1"/>
<f:selectItem itemValue="0"/>
</tr:selectOneRadio
Your backingBean looks somehow like this then:
public void yourValueChangeListener(ValueChangeEvent event)
{
if(event.getNewValue() == null)
return;
if((Integer)event.getNewValue() == 1)
{
//react on a change to 1
}
if((Integer)event.getNewValue() == 0)
{
//react on a change to 0
}
}
public int getYourIntValue() {
return yourIntValue;
}
public void setYourIntValue(int yourIntValue) {
this.yourIntValue = yourIntValue;
}

Highlight <p:inputText> if serverside validation get failed In PrimeFaces

I am trying to highlight an p:inputText (used to hold an email address) if this value doesn't match the value which came from the database. Here is my java code :
private UIInput gUiInputemailAdd; //global variable
public void validateCredentials(ComponentSystemEvent event) {
UIComponent components = event.getComponent();
UIInput uiInputemailAdd = (UIInput) components.findComponent("emailAdd");//ID of textbox
gUiInputemailAdd = uiInputemailAdd;
// uiInputemailAdd.setValid(false);//works fine here(it highlights this particular textBox)
}
public boolean forgotPasswordValidator(UserDetailTO userDetailTO)
throws MessagingException {
if (!gEmailAddress.equalsIgnoreCase(userDetailTO.getEmailAddress())) {
System.out.println(gUiInputemailAdd.getValue().toString()); //works fine and print value
gUiInputemailAdd.setValid(false);//doesn't work here
}
}
Xhtml code:-
<p:outputLabel for="emailAdd" value="EmilAddresss" />
<p:inputText value="#{loginTo.emailAddress}" id="emailAdd"/>
Please help me on this I have been stuck here for so long.

p:autoComplete not firing p:ajax event

I had this issue for a few hours and I surfed the net to try and find the solution but unfortunately I came up short.
Here is what I want to do.
I want to set p:outputText values when item in my autoComplete gets selected.
Here is the code:
<p:autoComplete
completeMethod="#{dynamicSearchBean.getCustomers}"
minQueryLength="1">
<p:ajax event="itemSelect"
listener="#{dynamicSearchBean.handleSelection}"
update="addName"/>
</p:autoComplete>
<h:outputText id="addName" value="#{dynamicSearchBean.firstName}"/>
And the backing bean:
public void handleSelection(SelectEvent event)
{
String value = (String) event.getObject();
System.out.println("selected "+value);
}//end method handleSelection
My autoComplete is working fine by getting values from DB but no event is being triggered when I select the value, and that is the main issue here.
Thanks for the help!
try this
public void handleSelection(SelectEvent event)
{
String value = (String) event.getObject();
this.firstName=value;
}//end method handleSelection

jsf. How to post backbean object from jsf form to javascript

I am using Primefaces/JSF in combination with pure javascript tools in order to implement an image viewer & annotator. Image viewer is built upon the OpenLayers framework.
When the user annotates (draws shapes) on the canvas, a JSON object is created and upon Save action passed to the back bean. Back bean retrieves the object (deserialized) and stores it in to a file.
Here is the relevant code:
OpenLayers javascript (image-viewer.js):
function initialiseMap(){'
...
map = new OpenLayers.Map(imageEditorID, options);
imageLayer = new OpenLayers.Layer.TMS(imgURL, "", {
...
});
map.addLayer(imageLayer);
var vlayer = new OpenLayers.Layer.Vector("Editable");
map.addLayer(vlayer);
//draw controls and shape tools
...
//then define save action
var save = new OpenLayers.Control.Button({
...
var GEOJSON_PARSER = new OpenLayers.Format.GeoJSON();
var vectorLayerAsJson = GEOJSON_PARSER.write(vlayer.features);
//and finally post to server layer with drawn shapes
sendJSONToServer([{name:'param', value:vectorLayerAsJson}]);
...
The above Image Viewer/Map tool, is loaded via an p:outputPanel component of primefaces and uses sendJSONToServer remoteCommand to get JSON layer:
<h:head>
<script src="#{facesContext.externalContext.requestContextPath}/js/image-viewer.js" />
...
<h:body>
<h:form id="imageEditor">
<p:fieldset legend="Viewer">
...
// inoutHidden does not have on* events? how am i going to post to image-viewer.js?
<h:inputHidden value="#{imageAnnotations.fetchJsonString()}" />
...
<p:outputPanel layout="block" styleClass="imageEditorImagePanel" />
<p:remoteCommand immediate="true" name="sendJSONToServer" action="#{imageAnnotations.actionOnString}" />
</p:fieldset>
....
Finally in the backbean the JSON object is fetched and stored in a file (implementation is raw):
#ManagedBean(name="imageAnnotations")
public class ImageAnnotations {
//actionOnString fetches and saves the JSON string - this is a raw impementation
public String actionOnString() {
//Do the job and get and save JSON string
}
public String fetchJsonString(){
//Do the job and get JSON string
return jsonString;
}
}
The question is How am i going to use a JSF or primefaces element to make available the imageAnnotations.fetchJsonString() value for fetching from within js?
Even I can't give all answers, for me the filling of your hiddenInput should be managed as following:
#ManagedBean(name="imageAnnotations")
public class ImageAnnotations {
private String jsonString;
public void anyMethodFillingOrInitializingTheJSONString() {
this.jsonString = resultOfYourWork();
}
public String getJsonString(){
return this.jsonString();
}
public void setJsonString(String item) {
this.jsonString = item;
}
}
When you reload this hidden input field, just be sure to trigger a javascript parsing the String and updating your client-side Model. This can be done via the on* - events you can connect with Primefaces buttons.
Guys, can anybody help with the other parts?

SelectOneMenu not displayed correctly

I would appreciate some input on the following issue:
I got one login screen followed by another page with a Panel and inside this Panel a SelectOneMenu. Unfortunatly the output of the SelectOneMenu after login is sometimes like this:
Instead the full(!) name of the User should be placed in the middle of the SelectOneMenu.
Sometimes it works, sometimes it doesn't.
Also if I switch User now, I only get the first letter of it. (Inside the dropdown the full name is written tho)
I populate the content inside a ManagedBean (#ViewScoped) in it's PostConstruct and get the data from database. (View -> ManagedBean -> DAO class -> ManagedBean).
I also tried to put the code inside public Classname{} with the same result.
I think there is a problem with the SelectOneMenu not correctly being rendered.
How to fix that?
users.xhtml:
<p:selectOneMenu id="somSelect" value="#{userManagerBean.somValue}"
styleClass="selecters">
<p:ajax update="userDataTable" listener="#{userManagerBean.changeSomValue}" />
<f:selectItems value="#{userManagerBean.userList}" />
</p:selectOneMenu>
ManagedBean #ViewScoped:
#PostConstruct
public void init() {
// DAO Method
retrieveTableData();
String loggedInUser = "";
try{
loggedInUser = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sprintUser").toString();
}catch(Exception e){
System.err.println("> No previous login");
}
// Check for session login name and select from table - if session null select first
if (somValue == null && userList.size() != 0) {
somValue = userList.get(0);
for(int i = 0; i < userList.size(); i++){
if(loggedInUser.equals(userList.get(i))){
somValue = loggedInUser;
}
}
}
selectedUser = somValue();
userData = new ArrayList<User>();
// a Table population
populateUser(userData);
}

Categories

Resources