How to pass data from one Managed Bean to another? [duplicate] - primefaces

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 4 years ago.
I am developing a website using JSF 2.2 and Primefaces 6.1 where I have, initially, 2 pages: A "list" page, where I can show the data to the user, and a "create" page, where I can create new data or edit existing ones.
NOTE: "Cargo" means occupation.
list.xhtml:
...
<h:form>
<p:commandButton value="Cadastrar" styleClass="ui-button-sucesso" action="create.xhtml?faces-redirect=true"/>
</h:form>
...
<h:form>
<p:dataTable value="#{cargoListMB.listaCargo}" var="cargo" rowKey="#{cargo.codigo}" emptyMessage="Nenhum cargo encontrado" filteredValue="#{cargoListMB.listaCargoFiltro}">
<f:facet name="header">Tabela de Cargos</f:facet>
<p:column headerText="Código" sortBy="#{cargo.codigo}" filterBy="#{cargo.codigo}" filterPosition="top">
<h:outputText value="#{cargo.codigo}"/>
</p:column>
<p:column headerText="Nome" sortBy="#{cargo.nome}" filterBy="#{cargo.nome}" filterPosition="top" filterMatchMode="contains">
<h:outputText value="#{cargo.nome}"/>
</p:column>
<p:column headerText="Funcionários" sortBy="#{cargo.funcionariosNesteCargo}"filterBy="#{cargo.funcionariosNesteCargo}" filterPosition="top">
<h:outputText value="#{cargo.funcionariosNesteCargo}"/>
</p:column>
<p:column headerText="Editar">
<p:commandButton icon="fa fa-pencil" title="Editar" styleClass="ui-button-icone-apenas" action="create.xhtml?faces-redirect=true">
<f:param name="objcargo" value="#{cargo.codigo}"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
CargoListMB.java:
#ManagedBean(name = "cargoListMB")
#ViewScoped
public class CargoListMB implements Serializable {
private List<Cargo> listaCargo;
private List<Cargo> listaCargoFiltro;
public List<Cargo> getListaCargo() {
if (listaCargo == null) {
listaCargo = CargoDAO.listarTodos(); //load data from database
}
return listaCargo;
}
public void setListaCargo(List<Cargo> listaCargo) {
this.listaCargo = listaCargo;
}
...
}
create.xhtml:
<h:form>
<f:metadata>
<f:viewParam name="objcargo" value="#{cargoCreateMB.cargo}" converter="cargoConverter"/>
<f:viewAction action="#{cargoCreateMB.inicializar()}"/>
</f:metadata>
<div class="ui-grid ui-grid-responsive">
<div class="ui-grid-row">
<div class="ui-grid-col-6">
<h1 class="if-page-title"><h:outputText value="#{cargoCreateMB.cargo.codigo == 0? 'Cadastro de Cargos' : 'Edição de cargo'}"/></h1>
</div>
<div class="ui-grid-col-6"></div>
</div>
<br/>
<div class="ui-grid-row">
<div class="ui-grid-col-12">
<div class="ui-grid-row">
<div class="ui-grid-col-1">
<p:outputLabel for="nome" value="Nome:"/>
</div>
<div class="ui-grid-col-3">
<p:inputText id="nome" placeholder="nome" value="#{cargoCreateMB.cargo.nome}" required="true""/>
</div>
<div class="ui-grid-col-8">
<p:message for="nome"/>
</div>
</div>
<br/>
<div class="ui-grid-row">
<div class="ui-grid-col-3">
<p:commandButton value="Salvar" actionListener="#{cargoCreateMB.salvar}" update="form" styleClass="ui-button-salvar"/>
</div>
<div class="ui-grid-col-9"></div>
</div>
</div>
</div>
</div>
</h:form>
CargoCreateMB.java
#ManagedBean(name = "cargoCreateMB")
#ViewScoped
public class CargoCreateMB implements Serializable {
private Cargo cargo;
public void salvar() {
try {
ControleCargo.insereCargo(cargo); //saves the 'occupation' on the database
MensagensUtil.mensagemInfo("Atenção", "Cargo inserido com sucesso");
} catch (RuntimeException e) {
MensagensUtil.mensagemInfo("Erro", "Erro ao inserir cargo");
System.out.println("Erro: " + e);
}
}
public void inicializar() {
//QUESTION!! : Due to a JSF page's life cycle, could I put this code on the constructor??
if (this.cargo == null) {
this.limpar();
}
}
private void limpar() {
cargo = new Cargo();
}
public Cargo getCargo() {
return cargo;
}
public void setCargo(Cargo cargo) {
this.cargo = cargo;
}
}
As you can see, I am trying to pass the selected 'occupation' from page list.xhtml to crate.xhtml using <f:param> and <f:viewParam> tags. When I click on button 'Cadastrar' (means 'register'), everything works fine (the "cargo" object is initially null, as expected), but when I click on the edit button, the "cargo.codigo" (occupation's ID) value, sent by the <f:param> tag, does not "arrive" to the "cargo" object. The converter ('cargoConverter') should be working fine, BUT, when I checked the String value that the method getAsObject was receiving, it was ALWAYS "0", no matter which occupation I choose on my list.
I also tried to send the "raw" data: Instead of using a converter, I sent the "cargo.codigo" value directly to a String field, but it was ALWAYS null.
Could someone help me discover what was my mistake? Also, if it is possible, is there another way to send data to other Managed Beans? Thanks in advance.
Edit: Based on Kukeltje's comments, I formatted my code (which can be seen above) and removed all the nested <h:form> elements BUT the problem still persists. Therefore, the answers on question How to use <h:form> in JSF page? didn't help at all and this question is not a duplicate.

Based on Kukeltje's comments and tips and the answers on this question, I managed to find my mistake: my <f:metadata> was indeed inside a <h:form>
tag. I removed it from there and it worked perfectly.

Related

Input element created with h:inputText is not editable

I'm creating a fieldText using h:inputText. I can type but when I click on it, it doesn´t select the text. It only puts the cursor at the end of the text. I've tried adding pointer-events: none; to CSS as I found on another question but with no result. Can anyone help?
Here is the JSF code:
<ui:define name="keyboard">
<a4j:outputPanel layout="block" styleClass="content">
<rich:panel id="kb">
<f:facet name="header">
<h:outputText id="keyboardHeading" value=""/>
</f:facet>
<h:inputText id="inputFieldKeyboard" value=""></h:inputText>
</rich:panel>
</a4j:outputPanel>
</ui:define>
The HTML turns into:
<div id="keyboard" class="dr-pnl rich-panel ">
<div id="keyboard_header" class="dr-pnl-h rich-panel-header ">
<span id="keyboardHeading"></span>
</div>
<div id="keyboard_body" class="dr-pnl-b rich-panel-body ">
<input id="inputFieldkeyboard" type="text" value="" name="inputFieldkeyboard"></input>
</div>
<div id="virtualKeyboard" class="virtual_keyboard"></div>
</div>
I've just found what the problem was, the element.contentEditable was set up to inherit. Not sure why it comes by default like this, I tried to add it to the DOM manually and also had the same problem, so I guess it´s related with a4j:outputPanel or rich:panel?
Now I get the element and set it up to true.

JSP Data table Limit number of rows on each div

I'm doing a page where i display some labels and input text field so the user can introduce some data and send it back to the server. But sometimes the server send back more than 50 rows of information. In this case the user need to scoll multiple times in order to see all the fields. I want to create 2/3 divs and each contains maybe ~20 fields so that all fields can be displayed without scrolling. Any idea?
Here is my code
<div class="container">
<div class="row">
<f:view>
<h:form>
<h:dataTable value="#{Message.bits}" var="bit">
<h:column>
<div class="col-lg-4">
<h:outputText value="#{bit.id} #{bit.name}" />
<div class="input-group">
<h:inputText styleClass="form-control" size="100"
maxlength="100" value="#{bit.value}" />
</div>
</p>
</div>
</h:column>
</h:dataTable>
</h:form>
</f:view>
</div>
</div>
Class Message -> A container of bits. It is a bean manager
#ManagedBean
#ViewScoped
public class Message implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2712306195992874273L;
private List<Bit> bits = null;
public List<Bit> getBits() {
return bits;
}
//Do more things
Bit class
public class Bit implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6341896264030346040L;
private String name = null;
private String value = null;
private int id = 0;
//Business logic
I can use html, css, any js framework, jsp,java.
Thanks for your time.
If I got your question right, you want to display your data like this:
1 4 7
2 5 8
3 6 9
Instead of this:
1
2
3
4
5
..
I don't know if this is the best solution but it works for me.
You can try the code below.
<div class="row">
<ui:repeat var="bit" value="#{message.bits}" varStatus="bitstatus">
<h:outputText escape="false" value="<div class='col-lg-4'>" rendered="#{(bitstatus.index + 1) % 20 eq 1}" />
<h:outputText value="#{bit.id} #{bit.name}" />
<div class="input-group">
<h:inputText styleClass="form-control" size="100" maxlength="100" value="#{bit.value}" />
</div>
<h:outputText escape="false" value="</div>" rendered="#{(productstatus.index + 1) % 5 eq 0}" />
</ui:repeat>
</div>

PropertyNotFoundException exporting datatable with column getting text from backingbean method

I have an primefaces datatable and column values also got displayed by using following code.
<c:forEach items="#{consolidatedReportByEquipmentBean.chairAmcDescList}" var="amcDescObj">
<c:forEach items="#{consolidatedReportByEquipmentBean.chairPartsList}"
var="partsObj">
<p:column style="text-align:center">
<p:outputLabel value="#{consolidatedReportByEquipmentBean.parseTotalNoOfPartsChanged(chairPartsRepairedObj.chairServiceAutoId,amcDescObj.amcDescAutoId,partsObj.chairPartsAutoId)}"></p:outputLabel>
</p:column>
</c:forEach>
By when i click datatable exporter,it results in following error.
javax.el.PropertyNotFoundException:
/Admin/Reports/Consolidate/EquipmentServicedRecord.xhtml #279,184 value="#{consolidatedReportByEquipmentBean.parseTotalNoOfPartsChanged(chairPartsRepairedObj.chairServiceAutoId,amcDescObj.amcDescAutoId,partsObj.chairPartsAutoId)}":
Property 'parseTotalNoOfPartsChanged' not found on type com.amcservicing.bean.ConsolidatedReportByEquipmentBean

How to disable <p:tab>

I want to disable <p:tab> using <p:commandButton>
File.xhtml
<h:form id="tabUserModule">
<p:tabView value="#{listModule.toArray()}" var="car" id="tabView1" widgetVar="delg1">
<p:tab title="#{car[0].module}" id="styleChoix" disabled="#{disableTag.disableTa}" >
<p:tabView orientation="left" >
<p:tab title=" Prototype " >
<h:panelGrid >
<p:commandButton value="Disable" oncomplete="delg1.select(0)"
action="#{disableTag.buttonAction}" update=":tabUserModule:tabView1:styleChoix"/>
.....
Bean.java
#ManagedBean
#ViewScoped
public class DisableTag implements Serializable {
private static final long serialVersionUID = 7179479455651980518L;
private boolean disableTa=false;
public boolean isDisableTa() {
return disableTa;
}
public void setDisableTa(boolean disableTa) {
this.disableTa = disableTa;
}
public void buttonAction()
{
disableTa = true;
}
}
But when i execute this code all tab are disabled so how can i solve this issue plz?
i want to disable tab surrounded by orange
You should change your update attribute to
update=":tabUserModule:tabView1"
only instead of your original ":tabUserModule:tabView1:styleChoix"
This means you have to update the whole p:tabView element instead of a specific tab only. Because upon inspection of the rendered html, this is a disabled="false" of your tab having the <div> as the <p:tabView> and the <li> and <a> combination as your individual <p:tab>:
<div id="tabUserModule:tabView1" ...>
<li class="ui-state-default ui-corner-top" ...>
....
</li>
</div>
but with disabled="true" it is rendered as:
<div id="tabUserModule:tabView1" ...>
<li class="ui-state-default ui-tabs-selected ui-state-active ui-corner-top ui-state-disabled" ...>
....
</li>
</div>
Notice the addition of the ui-state-disabled in the class attribute of the <li> tag which causes it to be disabled.
Hope this helps.

<pe:fluidGrid> not updating var in second iteration of <p:dataList>

I have a pe:fluidGrid within p:dataList wich reads elements from a hashmap.
I used to hava ui:repeat instead of p:dataList butt changed it due to this post: <h:form> within <ui:repeat> not entirely working, only the last <h:form> is processed
My Problem now is: that the inner fluidGrid is not correctly updating its var data.
<p:dataList var="pdi" value="#{FormGenerator.formItems.keySet()}" id="all" varStatus="loop" type="none" >
<p:panel id="panel" header="#{pdi.getFragmentDefinition().getFragmentName()}" style="margin-bottom:1em; width:100%;" >
<pe:fluidGrid id="fluidGrid" value="#{FormGenerator.formItems[pdi]}" var="data"
hGutter="20" vGutter="10" widgetVar="fluidGridWdgt_#{loop.index}" >
#{data.id} #{data.label}
<pe:fluidGridItem type="stringValue" id="txt_">
<div class="dynaFormLabel">
#{data.id}
<p:outputLabel for="txt" value="#{FormGenerator.formItems[pdi].get(data.id).getData().label} _ #{data.id}"/>
</div>
<p:inputText id="txt" value="#{FormGenerator.formItems[pdi].get(data.id).getData().value}"/>
</pe:fluidGridItem>
<pe:fluidGridItem type="integerValue" id="int_">
<div class="dynaFormLabel">
#{data.id}
<p:outputLabel for="int" value="#{FormGenerator.formItems[pdi].get(data.id).getData().label} _ #{data.id}"/>
</div>
<p:spinner id="int" value="#{FormGenerator.formItems[pdi].get(data.id).getData().value}" />
</pe:fluidGridItem>
<pe:fluidGridItem type="dateValue" id="cal_">
<div class="dynaFormLabel">
#{data.id}
<p:outputLabel for="cal" value="#{FormGenerator.formItems[pdi].get(data.id).getData().label} _ #{data.id}"/>
</div>
<p:calendar id="cal" value="#{FormGenerator.formItems[pdi].get(data.id).getData().value}" showOn="button"/>
</pe:fluidGridItem>
</pe:fluidGrid>
</p:panel>
</p:dataList>
Each Panel in the screenshot is created within the p:dataList. As you can see highlighted in red, The second panel starts with the last value of the first panel. The second panel is not complete du to a then occuring index out of bound exception (trying to access the 3rd index in a list of size 2).
Apparently all i had to do was change
#{FormGenerator.formItems[pdi].get(data.id).getData().label} to
#{FormGenerator.formItems[pdi][data.id].getData().label}
Anyone got any insights in what the difference is?