JSF InputText issue in DataTable - jsf

I have problem with InputText. When I try to get the InputText value after clicking the button, the value is null.
When I create the login page, there isn't a problem but using a DataTable does.
package controller;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import model.Groups;
import model.Student;
import util.DataHolder;
#ManagedBean(name = "edit", eager = true)
#SessionScoped
#RequestScoped
public class EditController implements Serializable {
private static final long serialVersionUID = 1L;
private List<Student> studentList;
private Groups group;
#PostConstruct
public void init() {
this.group = DataHolder.getGroup();
}
public List<Student> getStudentList() {
studentList = group.getStudents();
return studentList;
}
public void saveGrade(Student student) {
System.out.println(student.getName() + " " + student.getSurname() + "grade =" + student.getGrade());
}
public Groups getGroup() {
return group;
}
public void setGroup(Groups group) {
this.group = group;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
}
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Edit Page</title>
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css"></link>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script
src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></link>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"></link>
<script>
$(document).ready(function() {
$('#example').DataTable();
});
</script>
<h:body>
<div class="container">
<h:dataTable value="#{edit.studentList}" var="student"
styleClass="table table-striped table-bordered" id="example">
<h:column headerText="Student">
<f:facet name="header">
<h:outputLabel>Student</h:outputLabel>
</f:facet>
<h:outputText value="#{edit.studentList.indexOf(student) + 1}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputLabel>Number</h:outputLabel>
</f:facet>
<h:outputText value="#{student.no}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputLabel>Name</h:outputLabel>
</f:facet>
<h:outputText value="#{student.name}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputLabel>Surname</h:outputLabel>
</f:facet>
<h:outputText value="#{student.surname}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputLabel>Grade</h:outputLabel>
</f:facet>
<h:column>
<h:form>
<h:inputText value="#{student.grade}" class="form-control"></h:inputText>
</h:form>
</h:column>
</h:column>
<h:column>
<h:form>
<h:commandButton class="btn btn-danger btn-sm" value="Save"
action="#{edit.saveGrade(student)}" />
</h:form>
</h:column>
<h:column>
<h:form>
<h:commandButton class="btn btn-danger btn-sm" value="Delete"
action="#{edit.deleteStudent(student)}" />
</h:form>
</h:column>
</h:dataTable>
</div>
</h:body>
</html>

Related

Get to specific book using hyperlink in JSF [duplicate]

This question already has answers here:
Creating master-detail pages for entities, how to link them and which bean scope to choose
(2 answers)
Closed 7 years ago.
I have a very strange situation here. I have made my application in JSF and it looks just great, however I am not quite sure about following: I want to have a hyperlink so that once I click on my book title I get to a page with all the details regarding that book. My code looks so far:
My class looks like this:
package com.century.rental;
import javax.ejb.Stateless;
import javax.persistence.*;
import java.util.List;
#Stateless
public class GameEJB {
#PersistenceContext(unitName = "PerUni")
private EntityManager em;
public List<Game> findGames() {
TypedQuery<Game> query = em.createNamedQuery("Game.findAll", Game.class);
return query.getResultList();
}
public List<Game> findGamesByTitle(String title) {
TypedQuery<Game> query = em.createNamedQuery("Game.findByTitle", Game.class);
query.setParameter("title", title);
return query.getResultList();
}
public Game find(Long id) {
return em.find(Game.class, id);
}
public Game createGame(Game game) {
em.persist(game);
System.out.print("game stored");
return game;
}
}
My controller class looks like this:
package com.century.rental;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class GameController {
#EJB
private GameEJB gameEJB;
private Game game = new Game();
private String title = new String();
private List<Game> gameList = new ArrayList<Game>();
private List<Game> sgameList = new ArrayList<Game>();
public GameController() {
}
public String doCreateGame() {
gameEJB.createGame(game);
gameList = gameEJB.findGames();
game = new Game();
return "listGames.xhtml";
}
public Game getGame() {
return this.game;
}
public void setGame(Game game) {
this.game = game;
}
public List<Game> getGameList() {
gameList = gameEJB.findGames();
return gameList;
}
public void setGameList(List<Game> gameList) {
this.gameList = gameList;
}
public String searchGames() {
sgameList = gameEJB.findGamesByTitle(title);
return "resultsGames.xhtml";
}
public List<Game> getSgameList() {
return sgameList;
}
public void setSbookList(List<Game> sgameList) {
this.sgameList = sgameList;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Entity:
package com.century.rental;
import java.util.Date;
import javax.persistence.*;
#Entity
#NamedQueries({
#NamedQuery(name = "Game.findAll", query = "SELECT g FROM Game g"),
#NamedQuery(name = "Game.findByTitle", query = "SELECT g FROM Game g WHERE g.title = :title")
})
public class Game extends Product {
#Basic(optional = false)
#Column(name = "DEVELOPER_STUDIO", nullable = false, length = 100)
private String developerStudio;
#Basic(optional = false)
#Column(name = "PLATFORM", nullable = false, length = 100)
private String platform;
public Game() {
}
public Game(String title, String description, String rating, Date releaseDate, String developerStudio, String platform) {
super(title, description, rating, releaseDate);
this.developerStudio = developerStudio;
this.platform = platform;
}
public String getDeveloperStudio() {
return developerStudio;
}
public void setDeveloperStudio(String developerStudio) {
this.developerStudio = developerStudio;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
}
My HTML code looks like this:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>List of All Available Games in Database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</h:head>
<h:body>
<f:view>
<h:form>
<h1><h:outputText value="List of All Available Games in Database"/></h1>
<h:dataTable value="#{gameController.gameList}" var="item" border="1">
<h:column>
<f:facet name="header">
<h:outputText value="Id"/>
</f:facet>
<h:outputText value="#{item.id}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Title"/>
</f:facet>
<h:outputText value="#{item.title}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Description"/>
</f:facet>
<h:outputText value="#{item.description}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Rating"/>
</f:facet>
<h:outputText value="#{item.rating}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Release Date"/>
</f:facet>
<h:outputText value="#{item.releaseDate}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Developer Studio"/>
</f:facet>
<h:outputText value="#{item.developerStudio}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Platform"/>
</f:facet>
<h:outputText value="#{item.platform}"/>
</h:column>
</h:dataTable>
</h:form>
</f:view>
<br /><br />
Add New -OR- Go to Main Page
</h:body>
</html>
Please, help me I am not quite sure how can I make a hyperlink to a specific book from a list of books( as shown in the code )
Thanks.
P.S.
My specific page specificGame, which is supposed to get values from a game that was clicked in listGames page.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>List specific Game in Database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</h:head>
<h:body>
<f:view>
<h:form>
<h1><h:outputText value="List a specific Game in Database"/></h1>
<h:dataTable value="#{GameController.sGameList}" var="item" border="1">
<h:column>
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:outputText value="#{item.name}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Title"/>
</f:facet>
<h:outputText value="#{item.title}"/>
</h:column
</h:dataTable>
</h:form>
</f:view>
<br /><br />
Add New -OR- Go to Main Page
</h:body>
</html>
Now when I click on a title from the list of games on page list Games I would be redirected to specific Game page which is supposed to look like this: http://i.stack.imgur.com/OHmdp.png
populated by all the values from the particular game.
Try to change the column title in listGames.xhtml to :
<h:column>
<f:facet name="header">
<h:outputText value="Title"/>
</f:facet>
<h:commandLink value="#{item.title}" action="#{gameController.searchGames(item.title)}" />
</h:column>
Then, adapt the action method in the backing bean to :
public String searchGames(String tit) {
sgameList = gameEJB.findGamesByTitle(tit);
return "resultsGames.xhtml";
}

Commandbuttons problems

I have very strange problem. I can't use function in second button.
Steps:
1. Write forename and surename.
2. Click "find" button. Result: items in datatable.
3. Click "TEMPPP" only refresh page.
I have to use function sendUserInformation()
Administrator.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ace="http://www.icefaces.org/icefaces/components"
template="/WEB-INF/templates/template.xhtml">
<ui:define name="menuItems">
</ui:define>
<ui:define name="logedContent">
<h:form id="form1t">
<center><h:outputLabel value="#{msg.find_employee}"/></center>
<table class="tableGeneral">
<tr>
<td><h:outputLabel value="#{msg.forename}*"/></td>
<td>
<h:inputText id="name1" value="#{administrationController.forename}">
<f:validator validatorId="DefaultStringValidator"/>
</h:inputText>
</td>
<td>
<h:message styleClass="error" for="name1"/>
</td>
</tr>
<tr>
<td><h:outputLabel value="#{msg.surename}*"/></td>
<td>
<h:inputText id="name2" value="#{administrationController.surename}">
<f:validator validatorId="DefaultStringValidator"/>
</h:inputText>
</td>
<td>
<h:message styleClass="error" for="name2"/>
</td>
</tr>
<tr>
<td colspan="2">
<h:commandButton styleClass="buttonGeneral" value="#{msg.find}" >
<!-- <f:ajax event="click" execute="name1 name2" render=":form1t:form2:tab" listener="#{administrationController.find_employee()}"/> -->
<f:ajax event="click" execute="name1 name2" render="#all" listener="#{administrationController.find_employee()}"/>
</h:commandButton>
</td>
</tr>
</table>
</h:form>
<hr/>
<br/>
<h:form id="form2">
<center><h:outputLabel value="#{msg.found}"/></center>
<h:dataTable id="tab" value="#{administrationController.foundUsers}" styleClass="tableGeneral" var="o">
<h:column>
<f:facet name="header"><h:outputLabel value="#{msg.forename}"/></f:facet>
<h:outputText value="#{o.forename}"/>
</h:column>
<h:column>
<f:facet name="header"><h:outputLabel value="#{msg.surename}"/></f:facet>
<h:outputText value="#{o.surename}"/>
</h:column>
<h:column>
<f:facet name="header"><h:outputLabel value="#{msg.job}"/></f:facet>
<h:outputText value="#{o.job}"/>
</h:column>
<h:column>
<f:facet name="header"><h:outputLabel value="#{msg.user}"/></f:facet>
<h:outputText value="#{o.login}"/>
</h:column>
<h:column>
<f:facet name="header"><h:outputLabel value="#{msg.activated}"/></f:facet>
<h:outputText value="#{msg.yes}" rendered="#{o.activated}"/>
<h:outputText value="#{msg.no}" rendered="#{!o.activated}"/>
</h:column>
<h:column>
<!-- <h:commandButton value="TEMPPP #{o.id}" action="#{administrationController.sendUserInformation(o.id)}"/> -->
<!--
<h:commandButton value="TEMPPP #{o.id}" action="#{administrationController.sendUserInformation()}">
<f:param name="id" value="#{o.id}"/>
</h:commandButton>
-->
<h:commandButton value="TEMPPP #{o.id}" action="#{administrationController.sendUserInformation(o.id)}" styleClass="buttonGeneral" >
</h:commandButton>
<!--
<h:button value="TEMPPP #{o.id}" outcome="userInformation.xhtml">
<f:param name="id" value="#{o.id}"/>
</h:button>
-->
</h:column>
</h:dataTable>
</h:form>
</ui:define>
</ui:composition>
AdministrationController
package controller;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.context.FacesContext;
import others.MenuBars;
import database.Queries;
import users.User;
public class AdministrationController implements Serializable {
private static final long serialVersionUID = -2151888463865423931L;
private Queries queries = (Queries) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("queries");
private MenuBars menubars = (MenuBars)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("menuBars");
private List<User> users = new ArrayList<User>();
private List<User> foundUsers = new ArrayList<User>();
private String forename = "";
private String surename = "";
public AdministrationController(){
System.out.println("AdministrationController()");
users = queries.getAllUsers();
}
/*
public void tempUser(ValueChangeEvent event){
System.out.println(event.getNewValue().getClass());
User u = (User) event.getNewValue();
//TODO
System.out.println("idz do informacji o uzytkowniku"+u.name());
}*/
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
public String getSurename() {
return surename;
}
public void setSurename(String surename) {
this.surename = surename;
}
public void find_employee(){
System.out.println("find_employee()");
foundUsers.clear();
for(User u: users){
if(u.getForename().equalsIgnoreCase(getForename()) && u.getSurename().equalsIgnoreCase(getSurename())){
foundUsers.add(u);
}
}
}
public List<User> getFoundUsers() {
return foundUsers;
}
public void setFoundUsers(List<User> foundUsers) {
this.foundUsers = foundUsers;
}
public String sendUserInformation(String id){
System.out.println("sendUserInformation; id = "+id);
menubars.addToMap("id", id);
return "userInformation.xhtml";
}
}
SOLVED!
f:ajax was needed (and probably viewscope)
<h:commandButton action="#{administrationController.sendUserInformation(o.id)}" styleClass="buttonGeneral" value="TEMP #{o.id}">
<f:ajax/>
</h:commandButton>
Assuming that your AdministrationController bean is #RequestScoped (since you haven't specified it's scope), then the data in your <h:dataTable> will be reloaded per every request in the same view. This means, when you select
<h:commandButton value="TEMPPP #{o.id}" action="#{administrationController.sendUserInformation(o.id)}"/>
This will fire a new AdministrationController and the data in the List will be lost, which will break your action since o.id is not available anymore.
To solve this, use a wider scope like #ViewScoped at least.
#ManagedBean
#ViewScoped
public class AdministrationController implements Serializable {
//rest of your code
}

Form behaviour when using ajax to include a XHTML file

I'm learning about JSF and am trying to do a tabbed pane following this tutorial:
Tab manager using Ajax and JSF
I have managed to get the tab switch working. Now I want to include a form defined in another XHTML file as tab for this tabbed pane in which there's a dataTable with a commandButton to delete the selected row, called clientes.xhtml. If I navigate directly to this page then delete button works as expected. But when I include this page within contentForm it shows as expected but delete button doesn't do what is supposed to do, it just refresh the current page but no row is deleted.
This is what I have so far:
welcome.xhtml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns="http://www.w3.org/1999/xhtml"
template="./templates/BasicTemplate.xhtml">
<ui:define name="menu_bar">
<h:form id="formMenu">
<ul id="menu-list">
<li><h:commandLink value="Home">
<f:ajax event="click" render=":contentForm" listener="#{tabViewManagedBean.setTabIndex(0)}" />
</h:commandLink></li>
<li><h:commandLink value="Clientes">
<f:ajax event="click" render=":contentForm" listener="#{tabViewManagedBean.setTabIndex(1)}" />
</h:commandLink></li>
<li><h:commandLink value="Proveedores">
<f:ajax event="click" render=":contentForm" listener="#{tabViewManagedBean.setTabIndex(2)}" />
</h:commandLink></li>
</ul>
</h:form>
</ui:define>
<ui:define name="content">
<h:form id="contentForm">
<h:panelGroup layout="block" rendered="#{tabViewManagedBean.tabIndex == 0}">
<h1>Hi there!</h1>
<hr />
</h:panelGroup>
<h:panelGroup layout="block" rendered="#{tabViewManagedBean.tabIndex == 1}">
<ui:include src="clientes.xhtml" />
</h:panelGroup>
<h:panelGroup layout="block" rendered="#{tabViewManagedBean.tabIndex == 2}">
<ui:include src="proveedores.xhtml" />
</h:panelGroup>
</h:form>
</ui:define>
</ui:composition>
clientes.xhtml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns="http://www.w3.org/1999/xhtml">
<h:form>
<h:dataTable id="dataTable" value="#{clientesManagedBean.listaClientes}" var="cliente">
<h:column>
<f:facet name="header">
<h:outputText value="Id" />
</f:facet>
<h:outputText value="#{cliente.idCliente}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Fecha de ingreso" />
</f:facet>
<h:outputText value="#{cliente.fechaIngreso}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Nombre" />
</f:facet>
<h:outputText value="#{cliente.nombre}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Domicilio" />
</f:facet>
<h:outputText value="#{cliente.domicilio}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Teléfono" />
</f:facet>
<h:outputText value="#{cliente.telefono}" />
</h:column>
<h:column>
<f:facet name="header" />
<h:commandButton image="./resources/css/delete_16.png" action="#{clientesManagedBean.eliminarCliente(cliente)}"/>
</h:column>
</h:dataTable>
</h:form>
</ui:composition>
Edit 1
Here is the ClientesManagedBean code:
ClientesManagedBean.java
import beans.interfaces.IClientesBeanLocal;
import domain.entities.ClienteJpa;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
#ManagedBean
#ViewScoped
public class ClientesManagedBean {
#EJB(beanName = "ClientesBeanJpa")
private IClientesBeanLocal clientesBeanLocal;
private List<ClienteJpa> listaClientes;
private ClienteJpa cliente;
#PostConstruct
public void init() {
listaClientes = new ArrayList<>();
listaClientes.addAll(clientesBeanLocal.getTodos());
}
public List<ClienteJpa> getListaClientes() {
return listaClientes;
}
public ClienteJpa getCliente() {
return cliente;
}
public void eliminarCliente(ClienteJpa cliente) {
if(clientesBeanLocal.eliminar(cliente) == IClientesBeanLocal.EXITO) {
listaClientes.remove(cliente);
}
}
}
And ClientesBeanJpa session bean, just in case:
ClientesBeanJpa.java
import beans.interfaces.IClientesBeanLocal;
import domain.entities.ClienteJpa;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless(name = "ClientesBeanJpa")
public class ClientesBeanJpa implements IClientesBeanLocal {
#PersistenceContext(unitName = "CursoJ2eePU")
private EntityManager entityManager;
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public int eliminar(ClienteJpa cliente) {
if(entityManager == null) {
String error = "Error al inyectar EntityManager en la clase " + getClass().getCanonicalName();
throw new ExceptionInInitializerError(error);
} else {
ClienteJpa clienteAEliminar = entityManager.getReference(ClienteJpa.class, cliente.getIdCliente());
entityManager.remove(clienteAEliminar);
return EXITO;
}
}
}
Edit 2
Based on #Luiggi's suggestion I've tested if ClientesManagedBean#eliminar(cliente) method is even called and I've found this out:
If tabIndex property is set to 1 by default, then clientes.xhtml is rendered and it works as expected.
If tabIndex property is set to another value and then navigate to tab 1, then eliminar(cliente) is not even called.
Including TabViewManagedBean code just in case.
TabViewManagedBean.java
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
#ManagedBean
#ViewScoped
public class TabViewManagedBean {
private Integer tabIndex = 0;
/*
* If I set tabIndex to 1 then clientes.xhtml is rendered by default
* and everithing works as expected.
* But if I set this property to 0 and then navigate to tab 1 then it
* behaves as described.
*/
public TabViewManagedBean() {
super();
}
public Integer getTabIndex() {
return tabIndex;
}
public void setTabIndex(Integer tabIndex) {
this.tabIndex = tabIndex;
}
}
The problem is that you're nesting <form>, which is invalid HTML. This can be noted by this code:
welcome.xhtml:
<ui:define name="content">
<h:form id="contentForm">
<!-- code here... -->
<h:panelGroup layout="block" rendered="#{tabViewManagedBean.tabIndex == 1}">
<!-- including source of clientes.xhtml page -->
<ui:include src="clientes.xhtml" />
</h:panelGroup>
<!-- code here... -->
</h:form>
</ui:define>
And in clientes.xhtml you have:
<h:form>
<h:dataTable id="dataTable" value="#{clientesManagedBean.listaClientes}" var="cliente">
<!-- more code... -->
</h:dataTable>
<h:form>
Which ends in this way:
<h:form id="contentForm">
<!-- code here... -->
<h:panelGroup layout="block" rendered="#{tabViewManagedBean.tabIndex == 1}">
<h:form>
<h:dataTable id="dataTable" value="#{clientesManagedBean.listaClientes}" var="cliente">
<!-- more code... -->
</h:dataTable>
<h:form>
</h:panelGroup>
<!-- code here... -->
</h:form>
Decide where to define the <h:form> to not have nested forms. IMO you should define the <h:form> in the narrowest possible scope, which in this case will be in clientex.xhtml page only (and in the pages to include).
More info:
commandButton/commandLink/ajax action/listener method not invoked or input value not updated (your scenario resembles case 2 of the accepted answer)

How to display text in a dialog box?

The Data that I have entered in the input text field of the prime faces data table is not displayed in the dialog box JSF file and Data is not displayed in the dialog box
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Add/Remove Row</title>
</h:head>
<body>
<h:form id="form">
<p:dataTable id="buss" value="#{busBean.mediumBusModel}" var="bus"
selection="#{busBean.selectedBus}" selectionMode="single" >
<p:column headerText="Brand" style="width:5%">
<p:inputText value="#{bus.brand}" />
</p:column>
<p:column headerText="Model" style="width:5%">
<p:inputText value="#{bus.model}" />
</p:column>
<p:column headerText="Action" style="width:10%">
<p:commandButton actionListener="#{busBean.addBus()}" icon="ui-icon-plus" update=":form" ajax="false" title="add"/>
<p:commandButton actionListener="#{busBean.removeBus(bus)}" icon="ui-icon-minus" update=":form" ajax="false" title="remove"/>
</p:column>
<f:facet name="footer">
<p:commandButton id="viewButton" value="View" icon="ui-icon-search"
update=":form:displayBus" oncomplete="PF('singleBusDialog').show()"/>
</f:facet>
</p:dataTable>
<br/>
<p:dialog id="dialog" header="Bus Detail" widgetVar="singleBusDialog" resizable="false"
showEffect="fade" hideEffect="explode">
<h:panelGrid id="displayBus" columns="2" cellpadding="4">
<h:outputText value="Brand:" />
<h:outputText value="#{bus}" style="font-weight:bold"/>
<h:outputText value="Model:" />
<h:outputText value="#{bus}" style="font-weight:bold"/>
</h:panelGrid>
</p:dialog>
</h:form>
</body>
</html>
Below is the bean class that I have used
package com.bus.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import com.bus.bean.Bus;
#ManagedBean
#SessionScoped
public class BusBean implements Serializable {
private List<Bus> busList;
private Bus selectedBus;
private BusDataModel mediumBusModel;
public BusBean() {
busList=new ArrayList<Bus>();
busList.add(new Bus("a","b"));
mediumBusModel = new BusDataModel(busList);
//populateRandomCars(cars, 50);
}
public List<Bus> getBusList()
{
return busList;
}
public void setBusList(List<Bus> busList) {
this.busList = busList;
}
public void addBus()
{
Bus newBus=new Bus();
busList.add(newBus);
}
public Bus getSelectedBus() {
return selectedBus;
}
public void setSelectedBus(Bus selectedBus) {
this.selectedBus = selectedBus;
}
public void removeBus(Bus bus)
{
busList.remove(bus);
}
public BusDataModel getMediumBusModel() {
return mediumBusModel;
}
}
-------------------------------------------------------
package com.bus.bean;
import java.util.List;
import javax.faces.model.ListDataModel;
import com.bus.bean.Bus;
import org.primefaces.model.SelectableDataModel;
public class BusDataModel extends ListDataModel<Bus> implements SelectableDataModel<Bus> {
public BusDataModel() {
}
public BusDataModel(List<Bus> data) {
super(data);
}
#Override
public Bus getRowData(String rowKey) {
//In a real app, a more efficient way like a query by rowKey should be implemented to deal with huge data
List<Bus> buss = (List<Bus>) getWrappedData();
for(Bus bus : buss) {
if(bus.getModel().equals(rowKey))
return bus;
}
return null;
}
#Override
public Object getRowKey(Bus bus) {
return bus.getBrand();
}
}
-----------------------------------------------------------------------------------------------/
package com.bus.bean;
import java.io.Serializable;
public class Bus implements Serializable
{
public String model;
public String brand;
public Bus()
{
}
public Bus(String Model,String Brand)
{
this.model = model;
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getBrand() {
System.out.println("in set:"+brand);
return brand;
}
public void setBrand(String brand) {
System.out.println("in set:"+brand);
this.brand = brand;
}
#Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(obj instanceof Bus))
return false;
Bus compare = (Bus) obj;
return compare.model.equals(this.model);
}
#Override
public int hashCode() {
int hash = 1;
return hash * 31 + model.hashCode();
}
#Override
public String toString() {
return "Bus{" + "model=" + model + ", brand=" + brand + '}';
}
enter code here
}
Please let me know how to get the data that I have entered in the text field of Primefaces data table to the dialog box
You should use the selected value from the datatable.
selection="#{busBean.selectedBus}"
So , in your dialog box
<h:outputText value="Brand:" />
<h:outputText value="#{busBean.selectedBus.brand}" />
Also,
<p:commandButton id="viewButton" value="View" icon="ui-icon-search"
update=":form:displayBus,:form:dialog" oncomplete="PF('singleBusDialog').show()"/>
Updating the dialog box with value of the selected row.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Add/Remove Row</title>
</h:head>
<body>
<h:form id="form">
<p:growl id="messages" showDetail="true"/>
<p:contextMenu for="buss">
<p:menuitem value="Edit Cell" icon="ui-icon-search" onclick="PF('busTable').showCellEditor();return false; "/>
</p:contextMenu>
<p:dataTable id="buss" var="bus" value="#{busBean.busModel}" editable="true" editMode="cell" widgetVar="busTable"
selection="#{busBean.selectedBus}">
<p:ajax event="cellEdit" listener="#{busBean.onCellEdit}" update=":form:messages" />
<p:column selectionMode="single" style="width:2%" />
<p:column headerText="Brand" style="width:25%">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{bus.brand}" /></f:facet>
<f:facet name="input"><p:inputText id="brandInput" value="#{bus.brand}" style="width:96%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Model" style="width:25%">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{bus.model}" /></f:facet>
<f:facet name="input"><p:inputText id="modelInput" value="#{bus.model}" style="width:96%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Action" style="width:10%">
<p:commandButton actionListener="#{busBean.addBus()}" icon="ui-icon-plus" update=":form" ajax="false" title="add"/>
<p:commandButton actionListener="#{busBean.removeBus(bus)}" icon="ui-icon-minus" update=":form" ajax="false" title="remove"/>
</p:column>
<f:facet name="footer">
<p:commandButton id="viewButton" value="View" icon="ui-icon-search"
update=":form:buss,:form:displayBus,:form:dialog" oncomplete="PF('singleBusDialog').show()"/>
</f:facet>
</p:dataTable>
<br/>
<p:dialog id="dialog" header="Bus Detail" widgetVar="singleBusDialog" resizable="false"
showEffect="fade" hideEffect="explode">
<h:panelGrid id="displayBus" columns="2" cellpadding="4">
<h:outputText value="Brand:" />
<h:outputText value="#{busBean.selectedBus.brand}" style="font-weight:bold"/>
<h:outputText value="Model:" />
<h:outputText value="#{busBean.selectedBus.model}"/>

p:commandButton doesn't call bean's method in an <ui:include> page

I'm having a problem when I include dynamically a page with <ui:include>, the action and actionlistener associated with the <p:commandButton> component is not being invoked.
I've tried to remove the tag <h:form> from the included page but the problem persists.What can I do to solve this problem?
The source code:
hello.xhtm (Main Page)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<f:view>
<h:head>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<f:view contentType="text/html" />
</h:head>
<h:body>
<h:form id="helloForm">
<p:growl id="messages" />
<p:panelGrid id="panelGridPrincipal" styleClass="panelGridPrincipal">
<p:row>
<p:column colspan="2">
<div style="width: 100%; height: 25px; padding-left: 230px;">
<p:commandButton id="botao1" value="Bookmark" styleClass="button"/>
<p:commandButton id="botao2" value="Bookmark2" styleClass="button"
actionListener="#{mainBean.renderMenuVendas}" update="panel" >
<f:setPropertyActionListener value="2" target="#{mainBean.menuType}" />
</p:commandButton>
</div>
</p:column>
</p:row>
<p:row>
<p:column id="column2" style="width:200px;background-color: #5A5858;">
<h:panelGrid id="panel" styleClass="panelGridMenu" columns="1">
<p:menu id="dynamicMenu" model="#{mainBean.sideMenu}" rendered="#{mainBean.showMenuVendas}" style="width:189px;margin-right:100%;"/>
<p:spacer width="50px" height="700px" />
</h:panelGrid>
</p:column>
<p:column style="background-color: white">
<p:panelGrid style="border:1px;">
<p:row>
<p:column>
<p:outputPanel id="outputPanelConteudo">
<ui:include src="#{mainBean.paginaAtual}" />
</p:outputPanel>
</p:column>
</p:row>
<p:row/>
</p:panelGrid>
</p:column>
</p:row>
</p:panelGrid>
</h:form>
</h:body>
</f:view>
</html>
pagina1.xhtml (Included Page)
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<p:dataTable id="avioes" var="aviao" value="#{listaAvioesBean.aviao}"
rowKey="#{aviao.numeroSerie}"
selection="#{listaAvioesBean.selectedAviao}" selectionMode="single"
style="width:500px">
<p:column style="width:75px">
<f:facet name="header">
<h:outputText value="Numero de Serie" />
</f:facet>
<h:outputText value="#{aviao.numeroSerie}" />
</p:column>
<p:column style="width:100px">
<f:facet name="header">
<h:outputText value="Marca" />
</f:facet>
<h:outputText value="#{aviao.marca}" />
</p:column>
<p:column style="width:75px">
<f:facet name="header">
<h:outputText value="Modelo" />
</f:facet>
<h:outputText value="#{aviao.modelo}" />
</p:column>
<p:column style="width:75px">
<p:commandButton id="insertAviao" value="Inserir" title="Visualizar">
<f:setPropertyActionListener value="#{aviao}"
target="#{listaAvioesBean.selectedAviao}" />
</p:commandButton>
<!--THESE ACTION DOESN'T CALL THE BEAN METHOD!!! -->
<p:commandButton id="removerAviao" style="width:50px" value="P"
title="Deletar" action="#{listaAvioesBean.removerAviao}"
update=":helloForm:outputPanelConteudo">
<f:setPropertyActionListener value="#{aviao}"
target="#{listaAvioesBean.selectedAviao}" />
</p:commandButton>
</p:column>
</p:dataTable>
</ui:composition>
Managed bean (ListaAvioesBean.java)
package br.com.erp.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import br.com.erp.object.Aviao;
#ManagedBean(name="listaAvioesBean")
#ViewScoped
public class ListaAvioesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 8076960891132613195L;
private Aviao selectedAviao;
private List<Aviao> aviao;
public ListaAvioesBean(){
aviao = new ArrayList<Aviao>();
System.out.println("ListaAvioesBean Criado!");
}
#PostConstruct
public void init(){
System.out.println("Iniciando o bean!");
populateListAvioes();
}
public void executa(){
System.out.println("Executou");
}
private void populateListAvioes(){
Aviao av1 = new Aviao();
av1.setMarca("Marca1");
av1.setModelo("M1");
av1.setNumeroSerie("1234");
aviao.add(av1);
av1 = new Aviao();
av1.setMarca("Marca2");
av1.setModelo("M2");
av1.setNumeroSerie("1111");
aviao.add(av1);
av1 = new Aviao();
av1.setMarca("Marca3");
av1.setModelo("M3");
av1.setNumeroSerie("4321");
aviao.add(av1);
}
public Aviao getSelectedAviao() {
return selectedAviao;
}
public void setSelectedAviao(Aviao selectedAviao) {
this.selectedAviao = selectedAviao;
}
public List<Aviao> getAviao() {
return aviao;
}
public void setAviao(List<Aviao> aviao) {
this.aviao = aviao;
}
public void removerAviao(){
boolean removeu = aviao.remove(selectedAviao);
if(removeu)
System.out.println("Avião removido com sucesso");
}
public void executa(ActionEvent e){
System.out.println();
}
}

Resources