Primefaces selectOneMenu does not execute on change - java

I am writing a PrimeFaces application. I have the following code in my XHTML:
<p:selectOneMenu value="#{lottoCheckerBean.selectedPowerBallDrawingDate}">
<f:selectItems value="#{lottoCheckerBean.powerBallDrawingDates}" />
</p:selectOneMenu>
I am expecting the following code to be executed in my LottoCheckerBean when a value is selected:
public void setSelectedPowerBallDrawingDate(String selectedPowerBallDrawingDate) {
//get drawing
PowerBallDrawing currentDrawing = null;
for (int d = 0; d < powerBallDrawings.size(); d++) {
if (powerBallDrawings.get(d).getDrawingDate().equals(selectedPowerBallDrawingDate)) {
currentDrawing = powerBallDrawings.get(d);
break;
}
}
if (currentDrawing == null) {
try {
//create new drawing;
currentDrawing = new PowerBallDrawing(selectedPowerBallDrawingDate);
powerBallDrawings.add(currentDrawing);
Arrays.sort(powerBallDrawings.toArray());
} catch (Exception ex) {
//will not happen so ignore
}
}
this.selectedPowerBallDrawingDate = selectedPowerBallDrawingDate;
}
However, if I set a breakpoint at the beginning of the above method, the breakpoint is not reached.
What am I missing?

The code you expect to execute upon change will be called when you submit the form in which your selectOneMenu is placed. That is when the value from the selectOneMenu will be passed to your bean.
If you would want to perform something upon any other event, such as change, you need to enable ajax:
<p:selectOneMenu value="#{lottoCheckerBean.selectedPowerBallDrawingDate}" >
<f:selectItems value="#{lottoCheckerBean.powerBallDrawingDates}" />
<p:ajax event="change" listener="#{lottoCheckerBean.someMethod}" />
</p:selectOneMenu>
When value is changed in the backing bean, someMethod() will be called.
I would recommend you to use setSelectedPowerBallDrawingDate(String selectedPowerBallDrawingDate) only as a setter which sets the value, not to conatain any business logic at all. Then let the method you call from <p:ajax/> do the business logic.

Related

Primefaces ajax actionListener not called in p:selectOneMenu

This is my xhtml
<p:selectOneMenu
value="#{insurancePlanUpdateBean.insurancePlan.planType}">
<f:selectItems value="#{insurancePlanUpdateBean.planTypeList}" />
<p:ajax actionListener="#{insurancePlanUpdateBean.updatePlanType}"
event="change" update="form:panelHead" process="#this" />
</p:selectOneMenu>
from my code, action listener should call the updatePlanType in my updateBean,
i didnt get any error when running in eclipse, but when debugging, this program didnt get to the my updatePlanType class, there is my updatePlanType code :
public void updatePlanType(ActionEvent actionEvent) {
logger.debug("Update Plan Type");
try {
resetDetail();
if (insurancePlan.getPlanType().equals(
InsurancePlanConstants.PLAN_TYPE_MASTER)) {
if (insurancePlan.getInsuranceCompany() != null
&& insurancePlan.getInsuranceCompany().getCompanyName() != null
&& !StringUtils.isEmpty(insurancePlan
.getInsuranceCompany().getCompanyCode()))
existPlanType = true;
dependantAvailable = false;
existReference = false;
} else if (insurancePlan.getPlanType().equals(
InsurancePlanConstants.PLAN_TYPE_DEPENDANT)) {
if (insurancePlan.getInsuranceCompany() != null
&& insurancePlan.getInsuranceCompany().getCompanyName() != null
&& !StringUtils.isEmpty(insurancePlan
.getInsuranceCompany().getCompanyCode()))
existPlanType = true;
dependantAvailable = true;
existReference = true;
} else {
existPlanType = false;
existReference = false;
}
logger.debug("existPlanType:" + existPlanType);
logger.debug("dependantAvailable:" + dependantAvailable);
} catch (Exception e) {
logger.error("Error : ", e);
}
}
i think this would be a syntax problem, please help, im stuck for a couple of hours, thanks!
You are using the wrong event in your p:ajax statement.
Use:
<p:ajax actionListener="#{insurancePlanUpdateBean.updatePlanType}"
event="valueChange" update="form:panelHead" process="#this" />
or as valueChange already is the defaultEvent:
<p:ajax actionListener="#{insurancePlanUpdateBean.updatePlanType}"
update="form:panelHead" process="#this" />
instead of:
<p:ajax actionListener="#{insurancePlanUpdateBean.updatePlanType}"
event="change" update="form:panelHead" process="#this" />
You can find a list of the supported event types of every component in the documentation: https://primefaces.github.io/primefaces/8_0/#/components/selectonemenu?id=selectonemenu

pass SelectOneMenu value to add function in JSF / Primefaces

i'm using primefaces schedule , when the dialog form pop up , i need to select data from SelectOneMenu and pass them to the add function in order to insert them into database
the problem is that sometimes it works great and i can insert them, but when i try to add another second insert i doesn't work again
can you check it out please ? i need to know if i'm doing this the wrong way because i can't find the problem.
Managedbean constructor :
#PostConstruct
public void init() {
Chauffeurs = new ArrayList<Chauffeur>();
ChauffeurDispo = new dao.gsVoyage().getChauffeursDesponible(Chauffeurs);
model = new DefaultScheduleModel();
vDao=new dao.gsVoyage();
voyage=new Voyage();
try {
listVoyage=vDao.getListVoyages();
}catch(Exception ex) {
ex.printStackTrace();
FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR,"erreur","erreur no sql"));
}
for(Voyage v:listVoyage) {
DefaultScheduleEvent evt=new DefaultScheduleEvent();
evt.setEndDate(v.getDateV());
evt.setStartDate(v.getDateV());
evt.setDescription(v.getChauffeurBean().getMatricule());
evt.setData(v.getIdVoyage());
model.addEvent(evt);
}
}
the add function :
public void ajouter() {
try {
new dao.gsVoyage().addVoyage(dateV, autocar, chauffeur,chauffeur2,0);
DefaultScheduleEvent evt=new DefaultScheduleEvent();
evt.setEndDate(dateV);
evt.setStartDate(dateV);
evt.setDescription(chauffeur);
model.addEvent(evt);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", e.getMessage()));
}
voyage = new Voyage();
}
xhtml of SelectOneMenu :
<label>Chauffeur :</label><br/>
<h:selectOneMenu
value="#{scheduleJava8View.chauffeur}">
<f:selectItems
value="#{scheduleJava8View.chauffeurDispo}"
var="chauffeur" itemValue="#{chauffeur.matricule}"
itemLabel="#{chauffeur.nom}" />
</h:selectOneMenu>
this is how i display inserted data in xhtml
<label>Chauffeur:</label><br/>
<p:inputText value="#{scheduleJava8View.voyage.chauffeurBean.matricule}" />
Try changing your code to this
<h:selectOneMenu
onchange="submit()"
value="#{scheduleJava8View.chauffeur}">
This will make a call to
setChauffeur(Chauffeur c)
on your backed bean. Notice that in this case, you will need to define a converter since it is not a Java basic type (int, String,...).

Catch key pressed ajax event without input fields

In a partner management, when partner number or name is entered, the partner info and photo are shown and input text to introduce partner number or name is hidden.
Then I want to execute a method in my backing bean when ESC or ENTER key are pressed
I catch the keyup event with with following javascript in the view:
<script type="text/javascript">
$(document).bind('keyup', function(e) {
debugger;
if (arguments[0].key == 'Esc') {
alert("YEAH");
}
});
</script>
How can i call my backing bean method???
public void listener() {
switch (keyCode) {
case(27):
// switch boolean attribute in bean to render view hidden panel
}
}
I've tryed with remote command or ajax listener:
<p:remoteCommand name="remote" actionListener="#{registerVisitBean.listener}" update="input_table"/>
<f:ajax event="keyup" execute="#this keyCode" listener="#{registerVisitBean.listener}" update="input_table" />
<h:inputHidden id="keyCode" binding="#{keyCode}" value="#{registerVisitBean.keyCode}" />
Both methods catch the keyup when input text is selected but when i hide it to show partner info, listener stop working.
Any ideas?
Thanks!
J
<script type="text/javascript">
$(document).bind('keyup', function(e) {
debugger;
if (arguments[0].key == 'Esc') {
alert("YEAH");
// suppose you want to call your listener here
remote([{name: 'key', value: arguments[0].key}]);
}
});
</script>
<p:remoteCommand name="remote" actionListener="#{registerVisitBean.listener}" update="input_table"/>
public void listener() {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String keyCode = params.get("key");
// your code
}

JSF page is not showing the content

In system user can type a "URL", like "http://www.google.com" and this URL must be processed in SERVER and after the content is showed in XHTML page.
In my XHTML i have:
<h:form id="formNavegador" enctype="multipart/form-data">
<p:inputText value="#{navegadorMB.url}" required="true"
requiredMessage="A url é obrigatória"
type="Digite a url para navegar. Ex: http://www.google.com.br" />
<h:outputText value="#{navegadorMB.htmlContent}" escape="false"
id="htmlContent" />
<p:commandButton id="commandButtonProcessar" value="Ir"
update=":formNavegador:htmlContent" icon="ui-icon-play"
actionListener="#{navegadorMB.processaRequisicao}" />
</h:form>
So, when user type the URL and click in commandButton, the code bellow is processed:
public void processaRequisicao(ActionEvent event){
if (url.isEmpty()){
addErrorMessage("Você precisa digitar um endereço");
FacesContext.getCurrentInstance().validationFailed();
}else{
htmlContent = boPadrao.processaRequisicaoOnServer(url);
System.out.println(htmlContent);
}
}
In my method "processaRequisicaoOnServer" the URL is opened and all content is read, after the content of site is returned. See:
public String processaRequisicaoOnServer(String url) {
URL urlObj;
try {
urlObj = new URL(url.trim().toLowerCase());
BufferedReader conteudo = new BufferedReader(new InputStreamReader(urlObj.openStream()));
String linha = "";
StringBuffer sb = new StringBuffer();
while((linha = conteudo.readLine()) != null)
{
sb.append(linha);
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
throw new BOException(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new BOException(e.getMessage());
}
}
So, the content of URL is showed in console because of "System.out.." but the h:outputText is not updated as i hope.
I can't see your entire bean here, but here are some things that I've noticed:
If this is your entire form, you don't need the enctype="multipart/form-data", so you can just remove it.
There is a strange type attribute in your first p:inputText. Didn't you mean title?
<p:inputText type="Digite a url para navegar. Ex: http://www.google.com.br" />
Also, you don't need to specify the parent of a component when the component is already a child of this parent, so you could change this:
<p:commandButton id="commandButtonProcessar" value="Ir" update=":formNavegador:htmlContent" icon="ui-icon-play" actionListener="#{navegadorMB.processaRequisicao}" />
to this:
<p:commandButton id="commandButtonProcessar" value="Ir" update="htmlContent" icon="ui-icon-play" actionListener="#{navegadorMB.processaRequisicao}" />
And you are calling an action listener and passing an ActionEvent, which you don't need to, so you could change this:
public void processaRequisicao(ActionEvent event) { ...
to this:
public void processaRequisicao() { ...
Furthermore, in order to test it all, you could go in steps, creating a mock method first and checking if things are working properly, and then adding your business stuff.
For instance, to test this you could change your processaRequisicao to something like:
public void processaRequisicaoMock() {
htmlContent = "Funcionou!";
}
And then call it, and check if the view is working properly. If it is, you can go on, adding the business layer and all.
I hope it helps.
Instead of
<p:commandButton id="commandButtonProcessar" value="Ir"
update=":formNavegador:htmlContent" icon="ui-icon-play"
actionListener="#{navegadorMB.processaRequisicao}" />
Try
<p:commandButton id="commandButtonProcessar" value="Ir"
update="htmlContent" icon="ui-icon-play"
actionListener="#{navegadorMB.processaRequisicao}" ajax="false"/>
Also, change your method to
public void processaRequisicao(){
if (url.isEmpty()){
addErrorMessage("Você precisa digitar um endereço");
FacesContext.getCurrentInstance().validationFailed();
}else{
htmlContent = boPadrao.processaRequisicaoOnServer(url);
System.out.println(htmlContent);
}
}

How to populate certain text field after selecting item from <h:selectOneMenu /> JSF 2.0

i want that, when user select item in a inputText field populates with data from database.
I have a select menu list:
<h:selectOneMenu id="blah" value="#{controller.selected.id}" title="#{bundle.CreateTitle_id}" >
<f:selectItems value="#{controller.listOfId()}" />
</h:selectOneMenu>
and let's say have input text like this:
<h:inputText value="In here we place value from backing bean"></h:inputText>
How can i make after selecting an item from a list(which holds the id) populate text field with other data from my backing bean(let's say a name).
Here is my backingBean:
#ManagedBean(name = "controller")
#SessionScoped
public class Bean implements Serializable {
private Catalog current;// here i'm holding int id, String name and other stuff...
private DataModel items = null;
#EJB
private probaSession.CatalogFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public KatalogController() {
}
public Katalog getSelected() {
if (current == null) {
current = new Catalog();
selectedItemIndex = -1;
}
return current;
}
private KatalogFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
//......
public ArrayList<Catalog> listOfId() {
ArrayList<Catalog> list=new ArrayList<Catalog>();
try{
String upit="select id from Catalog";
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery(upit);
while(rs.next()) {
Katalog k=new Katalog();
k.setId(rs.getInt(1));
k.setName(rs.getString(2));
list.add(k);
}
disconnect();
}
catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
and that's pretty much it.
I'm here if anything needs to explaining. It think it is easy(using ajax let's say) but i don't even know how to start doing it...
You must add an f:ajax (that is standard, many component library offer extended versions) to catch a change event in the inputText
<h:selectOneMenu id="blah" value="#{controller.selected.id}" title="#{bundle.CreateTitle_id}" >
<f:selectItems value="#{controller.listOfId()}" />
<f:ajax
event="change" <-- The event to capture. I believe that if not specified
there is a default event to capture from
each component (for inputText it would be "change")
render="myForm:foo" <-- Only repaint "blah"
listener="#{controller.myBlahListener}"
</h:selectOneMenu>
<h:inputText id="foo" value="#{controller.fooText}"/>
Your listener will read the new value in this.getSelected().getId(), and change the model so that controller.getFooText() returns the new value (the easiest way probably is this.setFooTest(this.getSelected().getId(), but that depends of your model.

Categories