primefaces p:rowEdit cascading selectoneMenu - jsf-2

I have an Office datatable that displays department name and role name. department and role are objects. when I select rowedit, when there is a change in the department, the roles should be reloaded. I am not sure how to pass the selected department and rerender the roles.
<p:column headerText="Department">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{office.department.name}" /></f:facet>
<f:facet name="input">
<p:selectOneMenu value="#{office.department}" converter="#{departmentConverter}" style="width:96%" >
<f:selectItems value="#{departments}" var="dept" itemLabel="#{dept.name}" itemValue="#{dept}"/>
<p:ajax event="change" listener="#{officeManagmentController.onDepartmentChanged()}"/>
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Role">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{office.role.name}" /></f:facet>
<f:facet name="input">
<p:selectOneMenu value="#{office.role}" converter="#{roleConverter}" style="width:96%" >
<f:selectItems value="#{officeManagementController.assignableRoles}" var="role" itemLabel="#{role.name}" itemValue="#{role}"/>
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
the following is my officecontroller managedbean
#ConversationScoped
public class OfficeManagementController implements Serializable {
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage(selectedOffice.getName()+" selected");
selectedDepartment=selectedOffice.getDepartment();
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onDepartmentChanged() {
if(selectedOffice!=null)selectedSystem=selectedOffice.getDepartment();
log.info("Calling onDepartmentChanged " + ((selectedDepartment != null) ? selectedDepartment.getName() : "null"));
if(selectedDepartment != null) {
assignableRoles = roleRepo.findByDepartment(selectedDepartment);
for(int i=0;i<assignableRoles.size();i++){
System.out.println(assignableRoles.get(i));
}
} else {
assignableRoles=null;
}
}
}
What I noticed is the selectedOffice is null in the onDepartmentChanged() method, but in the onrowselect, the value is not null. I haven't progressed more than that. I have to dynamically change the roles when a department changes. Why is the selectedOffice null?

Related

Primefaces Extensions' Excel Exporter throws Property not found on type

I know this has been asked a lot. I already searched and tried multiple solutions, like this one but none of them work. Let me explain my problem:
I'm using Primefaces 4.0 with Primefaces Extensions 1.2.1. In a larger page I have this DataTable, which data I'd like to export to excel.
<p:dataTable id="t_resultados" value="#{buscarTramitesController.tablaProcesos}" var="proceso"
emptyMessage="No se han encontrado Trámites"
paginator="true" rows="10" paginatorPosition="top"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,50,100" lazy="true"
currentPageReportTemplate="Registros Totales: {totalRecords} Página: {currentPage} de {totalPages}"
selection="#{buscarTramitesController.procesoSeleccionado}" selectionMode="single"
rowKey="#{proceso.id}" resizableColumns="true" draggableColumns="true">
<p:column width="80" sortBy="#{proceso.nombre}">
<f:facet name="header"><p:outputLabel value="Nombre:"/></f:facet>
<p:outputLabel value="#{proceso.nombre}"/>
</p:column>
<p:column width="80" sortBy="#{proceso.tramite.expedienteAsociado.nombre}">
<f:facet name="header"><p:outputLabel value="Expediente:"/></f:facet>
<p:outputLabel value="#{proceso.tramite.expedienteAsociado.nombre}"/>
</p:column>
<p:column width="110" sortBy="#{proceso.fechaInicio}">
<f:facet name="header"><p:outputLabel value="Fecha de Inicio"/></f:facet>
<h:outputText value="#{proceso.fechaInicio}">
<f:convertDateTime pattern="dd/MM/yyyy hh:mm a"/>
</h:outputText>
</p:column>
<p:column width="140" sortBy="#{proceso.fechaFinalizacion}">
<f:facet name="header"><p:outputLabel value="Fecha de Finalización"/></f:facet>
<h:outputText rendered="#{proceso.fechaFinalizacion eq null}"
value="Proceso en marcha">
</h:outputText>
<h:outputText rendered="#{proceso.fechaFinalizacion ne null}" value="#{proceso.fechaFinalizacion}">
<f:convertDateTime pattern="dd/MM/yyyy hh:mm a"/>
</h:outputText>
</p:column>
<p:column width="120">
<f:facet name="header"><p:outputLabel value="Actividad actual"/></f:facet>
<h:outputText value="#{buscarTramitesController.NombreActividad(proceso)}">
</h:outputText>
</p:column>
<p:column width="120" >
<f:facet name="header"><p:outputLabel value="Aceptada por"/></f:facet>
<h:outputText value="#{buscarTramitesController.AceptadaPor(proceso)}">
</h:outputText>
</p:column>
<p:column width="170">
<f:facet name="header"><p:outputLabel value="Última actividad completada"/></f:facet>
<h:outputText value="#{buscarTramitesController.UltimaCompletada(proceso)}">
<f:convertDateTime pattern="dd/MM/yyyy hh:mm a"/>
</h:outputText>
</p:column>
<p:column>
<f:facet name="header"><p:outputLabel value="Completada por"/></f:facet>
<h:outputText value="#{buscarTramitesController.CompletadaPor(proceso)}">
</h:outputText>
</p:column>
<p:column width="80">
<f:facet name="header"><p:outputLabel value="Opciones"/></f:facet>
<p:commandLink immediate="true" value="Ver" actionListener="#{buscarTramitesController.abrirTramite(proceso.id)}"/>
</p:column>
<p:ajax event="rowDblselect" listener="#{buscarTramitesController.abrirTramite(buscarTramitesController.procesoSeleccionado.id)}"/>
</p:dataTable>
And my exporter looks like this:
<p:commandButton value="Exportar a Excel" id="b_exportar" ajax="false">
<pe:exporter type="xlsx" target="t_resultados" fileName="Lista de Tramites"/>
</p:commandButton>
I have several excel exporters in my application and only that one is giving problem. When I click that button, it throws the follow exception:
javax.servlet.ServletException: /busquedas/BuscarTramites.xhtml #124,100 value="#{buscarTramitesController.NombreActividad(proceso)}": Property 'NombreActividad' not found on type com.megagroup.mgestion.web.controller.busquedas.BuscarTramitesController
javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
It's the first method in that table which it tries to call.
These methods all looks the same, receives a Proceso (which is the object that's being displayed in the datatable) and returns a String:
My backing bean looks like this:
private Tarea ultimaTareaCompletada(Proceso proceso) {
List<Tarea> tareas = proceso.getTareas();
if (tareas == null || tareas.isEmpty()) {
return null;
}
List<Tarea> tareasCompletadas = new ArrayList<>();
for (Tarea tarea : tareas) {
if (tarea.getEstado().equals(EstadoTarea.COMPLETADA)) {
tareasCompletadas.add(tarea);
}
}
if (tareasCompletadas.isEmpty()) {
return null;
}
Collections.sort(tareasCompletadas, new Comparator<Tarea>() {
#Override
public int compare(Tarea t1, Tarea t2) {
if (t2.getFechaFinalizacion() == null) {
return 999;
}
if (t1.getFechaFinalizacion() == null) {
return 0;
}
return t2.getFechaFinalizacion().compareTo(t1.getFechaFinalizacion());
}
});
return tareasCompletadas.get(0);
}
public String UltimaCompletada(Proceso proceso) {
Tarea tarea = ultimaTareaCompletada(proceso);
if (tarea == null) {
return PROCESO_SIN_TAREAS;
} else if (tarea.getTipoTarea() == null) {
return TAREA_SIN_ACTIVIDAD;
} else if (tarea.getTipoTarea().getNombre() == null || tarea.getTipoTarea().getNombre().isEmpty()) {
return ACTIVIDAD_SIN_NOMBRE;
} else {
return tarea.getTipoTarea().getNombre();
}
}
public String CompletadaPor(Proceso proceso) {
Tarea tarea = ultimaTareaCompletada(proceso);
if (tarea == null) {
return PROCESO_SIN_TAREAS;
} else if (tarea.getNombreUsuario() == null) {
return COMPLETADA_SIN_USUARIO;
} else {
return tarea.getNombreUsuario();
}
}
private Tarea actividadActual(Proceso proceso) {
if (proceso.getTareas() == null || proceso.getTareas().isEmpty()) {
return null;
}
return proceso.getTareas().get(proceso.getTareas().size() - 1);
}
public String AceptadaPor(Proceso proceso) {
Tarea tarea = actividadActual(proceso);
if (tarea == null) {
return PROCESO_SIN_TAREAS;
}
if (tarea.getNombreUsuario() == null || tarea.getNombreUsuario().isEmpty()) {
return SIN_ACEPTAR;
}
return tarea.getNombreUsuario();
}
public String NombreActividad(Proceso proceso) {
Tarea tarea = actividadActual(proceso);
if (tarea == null) {
return PROCESO_SIN_TAREAS;
}
if (tarea.getTipoTarea().getNombre() == null || tarea.getTipoTarea().getNombre().isEmpty()) {
return ACTIVIDAD_SIN_NOMBRE;
}
return tarea.getTipoTarea().getNombre();
}
I though it was the methods' name, I already tried renaming them like that: getNombreActividad, nombreActividad, NombreActividad, getnombreActividad, but none of them worked. That problem is only showing when I click the export to excel button, the table display successful all the information from these methods.
Any help would be appreciated, thanks!
The exporter only accepts valueExpressions afaik and not methodExpressions. ValueExpressions consist of getters and setters of properties and getters do not accept parameters. So the resolving of the property fails as expected

page can't get value from Bean

I have a table p:dataTable. When I select an item, it's refresh another p:dataTable with associed values.
It's works fine. But when I select an item in the second table, the page (xhtml) don't get the value from the bean.
In debug mode I see that the value is updated on bean, but acessing #{bean.value} is always null.
Where is the codes:
<h:form id="form">
<h:panelGrid columns="2">
<!-- FRIST TABLE -->
<p:dataTable id="alunos" var="aluno" emptyMessage="Nenhum aluno cadastrado" value="#{alunos.usuarios}" selectionMode="single" selection="#{alunos.usuarioSelecionado}" rowKey="#{aluno.id}">
<f:facet name="header">
Alunos
</f:facet>
<p:ajax event="rowSelect" listener="#{alunos.onRowSelect}" update=":form:disci" />
<p:column headerText="Nome" width="60%">
<h:outputText value="#{aluno.nome}" />
</p:column>
<p:column headerText="Curso">
<h:outputText value="Default" />
</p:column>
</p:dataTable>
<!-- FUNCTIONS FOR FRIST TABLE THAT ARE WORKING -->
<p:column rowspan="4">
<p:commandButton value="Adicionar" update="alunos" icon="ui-icon-plus" actionListener="#{alunos.addUser()}"/>
<p:commandButton value="Editar" icon="ui-icon-pencil" actionListener="#{alunos.editarUser()}"/>
<p:commandButton value="Remover" icon="ui-icon-close" actionListener="#{alunos.apagaUser()}"/>
</p:column>
</h:panelGrid>
<p:outputLabel for="disci" value="Disciplinas que o aluno cursa" />
<!-- SECOND TABLE - Updated when an iten is selected in frist table (working)-->
<p:dataTable id="disci" var="disciplina" emptyMessage="Selecione um aluno" value="#{alunos.disciplinas}" selectionMode="single" selection="#{alunos.disciplinaSelecionada}" rowKey="#{disciplina.id}">
<p:ajax event="rowSelect" listener="#{alunos.onRowSelectDisciplina}" oncomplete="PF('dDialog').show()"/>
<p:column headerText="Nome" width="80%">
<h:outputText value="#{disciplina.nome}" />
</p:column>
</p:dataTable>
<!-- Dialog to show informations - ALWAYS NULL -->
<p:dialog header="Info" widgetVar="dDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="detail" style="text-align:center;">
<p:panelGrid columns="2" columnClasses="label,value">
<h:outputText value="Id:" />
<h:outputText value="#{alunos.disciplinaSelecionada.id}" />
<h:outputText value="Nome" />
<h:outputText value="#{alunos.disciplinaSelecionada.nome}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
And the Bean:
#ManagedBean(name = "alunos")
#ViewScoped
public class Alunos extends NovoUsuario {
private Disciplina disciplinaSelecionada;
public Alunos() {
super(TiposUsuario.ALUNO);
}
//Method called when an iten is selected in SECOND TABLE
//In debug, the Object Disciplina is correct, as selected in table.
public void onRowSelectDisciplina(SelectEvent event) {
this.disciplinaSelecionada = (Disciplina) event.getObject();
}
//getters and setters
}
extended class:
public class NovoUsuario implements Serializable{
private List<Usuario> usuarios;
protected Usuario usuarioSelecionado;
TiposUsuario tipo;
private String nome;
private String senha;
protected List<Disciplina> disciplinas;
//Constructor
public NovoUsuario(TiposUsuario tipo) {
this.tipo = tipo;
}
//Initialize FRIST TABLE
#PostConstruct
public void init() {
UsuarioCRUD usuarioCRUD = new UsuarioCRUD();
this.usuarios = usuarioCRUD.listarTipoUsuario(tipo);
}
//Method used in FRIST TABLE
public void onRowSelect(SelectEvent event) {
disciplinas = getDisciplinaUsuario();
}
//Method that get data to SECOND table when a row is selectd in frist
public List<Disciplina> getDisciplinaUsuario() {
DisciplinaCRUD dcrud = new DisciplinaCRUD();
if (usuarioSelecionado != null) {
return dcrud.listaDisciplinasUsuario(usuarioSelecionado);
}
return null;
}
public void salvaUsuario() {
/* code to create*/
}
public void editarUser(){
/* code to update*/
}
public void apagaUser(){
/* code to delete*/
}
//GETTERS AND SETTERS
}
image: http://i.stack.imgur.com/Qbs0T.png
repository: https://bitbucket.org/VagnerGon/novo-academico
I'd say you just need to update the dialogs content from the p:ajax in the second table - just as you update the second datatable, when you select in the first.
So add id="dialog" to the dialog, and make the p:ajax in the second table
<p:ajax event="rowSelect" listener="#{alunos.onRowSelectDisciplina}" update=":form:dialog" oncomplete="PF('dDialog').show()" />
Or omit the new id and just do update=":form:detail".

Value not setting in Backing Bean after putting render attribute

In the below code, the value of Price is not setting in backing bean after I set the render attribute. Prior to that It was setting into the backing Bean.
h:dataTable id="Table" value="#{bean.orderList}" var="attr" binding="#{bean.orderTable}">
<h:column>
<f:facet name="header">
<h:outputText value="Item"/>
</f:facet>
<h:outputText value="#{attr.orderItem.itemId}" rendered="#{attr.orderItem.itemId != null}" />
<h:selectOneMenu value="#{attr.orderItem.itemId}" rendered="#{attr.orderItem.itemId == null}">
<f:selectItems value="#{bean.itemList}" var="attrList" itemValue="#{attrList.itemId}" itemLabel="#{attrList.itemName}" />
</h:selectOneMenu>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Price" />
</f:facet>
<h:outputText value="#{attr.price}" rendered="#{attr.orderItem.itemId != null}" />
<h:inputText value="#{attr.price}" rendered="#{attr.orderItem.itemId == null}" />
</h:column>
Please find below the Code for bean
public String addAction() {
Order ord = new Order();
ord.setItems(new Items());
orderList.add(ord);
count=count+1;
return null;
}
#PostConstruct
public void populateForm(){
Order ord = new Order();
ord.setItems(new Items());
orderList= dataDao.getOrders();
ord.add(srcTrustScore);
}

row editable data table column with dialog in jsf

I am new to JSF. I am using row editable data table in JSF primefaces. In row editable datatable input text column it have two ajax calls.one is blur and another one is Commandbuuton. I want to get value from this input text column from backing bean.
Here is my Code:
<h:form id="frm1">
<p:dataTable var="fert" value="#{fertilizerEntryBean.fertList}" id="fertList" editable="true" scrollable="true" scrollWidth="900" scrollHeight="250" >
<p:ajax event="rowEdit" listener="#{fertilizerEntryBean.onEdit}" update=":frm1:messages :frm1:ha_amount" />
<p:ajax event="rowEditCancel" listener="#{fertilizerEntryBean.onCancel}" update=":frm1:messages :frm1:ha_amount" />
<p:column headerText="...." width="15">
<p:rowEditor />
</p:column>
<p:column headerText="Receiver Plot No." width="150">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{fert.receiverPlot}" /></f:facet>
<f:facet name="input">
<p:inputText id="receiverPlot" value="#{fert.receiverPlot}" size="15">
<p:ajax event="blur" listener="#{fertilizerEntryBean.loadReceiverDetails(fert)}" update="receiverCode,receiverName"/>
</p:inputText>
<p:commandButton icon="ui-icon-search" style="height: 25px;position: absolute;" onclick="receiver_dialog.show();"/>
</f:facet>
</p:cellEditor>
</p:column>
</p:datatable>
</h:form>
<h:form id="receiverForm">
<p:dialog widgetVar="receiver_dialog" id="receiver_dialog">
<p:dataTable id="receiver_table" value="#{fertilizerEntryBean.mediumFertModel}" selection="#{fertilizerEntryBean.selectedList}" selectionMode="single" var="fert" rows="10" liveScroll="true" paginator="true" paginatorPosition="bottom"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,20">
<p:ajax event="rowSelect" listener="#{fertilizerEntryBean.onRowSelect}" update=':frm1:fertList:receiverPlot'/>
<p:column id="state_id_column" headerText="Receiver Code">
<h:outputText value="#{fert.receiverPlot}"/>
</p:column>
</p:dataTable>
<p:commandButton style="alignment-adjust: central;" value='OK' onclick="receiver_dialog.hide();"/>
</p:dialog>
</h:form>
And my Bean Class:
public class FertilizerEntryBean implements Serializable{
private List<FertModel> fertList=null;
private FertDataModel mediumFertModel;
private FertModel selectedList;
public List<FertModel> getFertList() {
return fertList;
}
public void setFertList(List<FertModel> fertList) {
this.fertList = fertList;
}
public FertDataModel getMediumFertModel() {
getReceiverCode();
return mediumFertModel;
}
public void setMediumFertModel(FertDataModel mediumFertModel) {
this.mediumFertModel = mediumFertModel;
}
public FertModel getSelectedList() {
return selectedList;
}
public void setSelectedList(FertModel selectedList) {
this.selectedList = selectedList;
}
public List<FertModel> getReceiverCode(){
Session session=HibernateUtil.getSessionFactory().openSession();
try{
List<DosVendormaster> vendorList=session.createCriteria(DosVendormaster.class).add(Restrictions.eq("vendortype", "CGRV")).add(Restrictions.eq("block", "X")).list();
if(vendorList.size()>0){
for (Iterator<DosVendormaster> it = vendorList.iterator(); it.hasNext();) {
DosVendormaster dosVendormaster = it.next();
fertList.add(new FertModel(dosVendormaster.getSapVendorcode()));
}
mediumFertModel=new FertDataModel(fertList);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
session.close();
}
return fertList;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage(" Selected", ((FertModel) event.getObject()).getReceiverPlot());
FacesContext.getCurrentInstance().addMessage(null, msg);
FertModel fert=new FertModel();
fert.setReceiverPlot(((FertModel) event.getObject()).getReceiverPlot());
}
}
You can try this: FacesContext.getCurrentInstance().getViewRoot().findComponent(id) where id is something like frm1:fert:(rowIndex):receiverPlot. That's how you can find component and use getValue for that component. You can take rowIndex by setting rowIndexVar attributte to your datatable

<p:commandButton> does not invoke method when <p:column selectionMode="multiple"> is added

I have a <p:dialog> with a <p:dataTable> and a <p:commandButton>.
When I add <p:columm selectionMode="multiple"> to the table, then the button doesn't invoke the action listener method. Without that column, it works fine.
How is this caused and how can I solve it?
Here is my view:
<p:dialog id="CategoriasShowPadre" header="#{msgs['Categorias.BusquedaDeCategorias']}" widgetVar="CategoriasShowPadre" modal="true">
<p:dataTable id="DTBusquedaCategoriasPadre" widgetVar="posiblesTablaP" var="BcatP" value="#{agregarCategorias.categoriasPosibles}"
emptyMessage="#{msgs['Categoria.SinRegistros']}" rowKey="#{BcatP.nombre}" selection="#{agregarCategorias.categoriasPosiblesSelecionadas}">
<p:column selectionMode="multiple" style="width:18px" />
<p:column id="nombreCol" filterBy="#{BcatP.nombre}" filterMatchMode="contains">
<f:facet name="header">
<h:outputText value="#{msgs['Categoria.ColunmnaNombre']}" />
</f:facet>
<h:outputText value="#{BcatP.nombre}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="#{msgs['Categoria.ColunmnaDescripcion']}" />
</f:facet>
<h:outputText value="#{BcatP.descripcion}" />
</p:column>
</p:dataTable>
<p:commandButton id="AnadiraPadre" value="#{msgs['Categoria.Boton.AgregarCategorias']}"
immediate="true" actionListener="#{agregarCategorias.selecionadosElementosPadres()}"
onclick="CategoriasShowPadre.hide();" />
</p:dialog>
Here is the backing bean:
#ManagedBean
#RequestScoped
public class AgregarCategorias {
private List<Categorias> CategoriasPosibles;
private List<Categorias> CategoriasPosiblesSelecionadas;
#PostConstruct
private void MiPostConstructor() {
this.CategoriasPosibles = // ...
}
public List<Categorias> getCategoriasPosiblesSelecionadas() {
return CategoriasPosiblesSelecionadas;
}
public void setCategoriasPosiblesSelecionadas(List<Categorias> CategoriasPosiblesSelecionadas) {
this.CategoriasPosiblesSelecionadas = CategoriasPosiblesSelecionadas;
}
public List<Categorias> getCategoriasPosibles() {
return CategoriasPosibles;
}
public void setCategoriasPosibles(List<Categorias> CategoriasPosibles) {
this.CategoriasPosibles = CategoriasPosibles;
}
public void selecionadosElementosPadres(ActionEvent evento) {
// my method code
}
}
The 'selection' attribute of the datatable should reference an array of the domain object.
So change private List<Categoria> CategoriasPosiblesSelecionadas for private Categoria[] CategoriasPosiblesSelecionadas

Resources