i'm trying to open a popup mailto by using two different codes:
(1)- <p:link href="mailto:#{classManagedBean.sendEmails}" />
(2)- <p:commandlink actionListener="#{candidatManagedBean.sendEmails()}" />
the "senEmails" is a method declared in the classManagedBean in order to get all the selected emails when a submit of the form done.
The issus that i encountred that when:
working with the code (1) the selected mails came to the managedBean with null values and a popup of the mail interface open with empty mails (as destination)
with the code (2) the selected mails came with the correct values but the popup didn't appear (beacause there is no href attribut!! in the commandLink)
My question is how can i use a
<p:link> with a submit form
<p:commandLink> with href attribut
The Xhtml:
<h:form id="form">
<p:link href="#{candidatManagedBean.createmaito()}">
<p:graphicImage width="25" value="ecrire.png" height="25" alt="envoyer"/>
</p:link>
</h:form>
<p:dataTable id="listCandidat"
value="#{candidatManagedBean.listCandidat}"
emptyMessage="0 candidat trouvé"
var="item"
paginator="true" rows="15" paginatorPosition="bottom"
rowKey="#{item.idCandidat}"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
lazy="true"
selection="#{candidatManagedBean.selectedCandidates}"
>
<p:ajax event="rowSelect" listener="#{candidatManagedBean.onRowSelect}" />
<p:column exportable="false" selectionMode="multiple" style="width:16px;text-align:center"/>
{<p:column>...</p:column>}
</p:dataTable>
The managedBean:
public String createmaito() { // private List<Candidat> selectedCandidates;
System.out.println(selectedCandidates);//here i got a null value of selectedCandidates
if (selectedCandidates != null && !selectedCandidates.isEmpty()) {
for (Candidat cand : selectedCandidates) {
lsEmail = lsEmail.concat(cand.getEmail1());
lsEmail = lsEmail.concat(",");
}
lsEmail= lsEmail.substring(0, lsEmail.length()-1);
result = lsEmail;
}
else {
result = "";
}
return result;
}
I got the solution as follows:
-In XHTML:
<p:commandLink actionListener="#{ManagedBean.getListeOfEmailContacts()}">
<p:graphicImage value="/mail.png" />
</p:commandLink>
-In managed bean:
public void getListeOfEmailContacts() {
/* instruction to get the ListOfContacts ...*/
RequestContext.getCurrentInstance().execute("window.open(href ='mailto:" + ListOfContacts + "')");
}
Related
I have a selectonemenu within a datatable column. The selected options are messed up when I delete a row and it doesn't seems to reflect the value in the backend bean. For example, I selected Item A in the first row, then add another row and select Item B in the second row, then when I delete the first row, the second row is move up with Item A selected, but the backend value of second row is still Item B and Item A is removed from the collection.
<p:dataTable id="insertDetailTable" styleClass="data-table"
rowIndexVar="rowIndex" var="receivingDetail"
value="#{receivingController.receiving.receivingDetails}">
<p:column headerText="Item">
<p:selectOneMenu styleClass="input" id="item"
value="#{receivingDetail.item}" required="true"
requiredMessage="Item is required" converter="itemConverter">
<f:selectItem itemLabel="Select an item" itemValue="#{null}"
noSelectionOption="true" />
<f:selectItems value="#{receivingController.items}" var="item"
itemLabel="#{item.code} - #{item.name}" itemValue="#{item}" />
<p:ajax update="insertDetailTable" />
</p:selectOneMenu>
</p:column>
<p:column styleClass="action-cell">
<f:facet name="header">
<p:commandButton icon="ui-icon-plus" value="Add"
action="#{receivingController.insertDetail('insert')}"
immediate="true" />
</f:facet>
<p:commandButton icon="ui-icon-trash"
action="#{receivingController.deleteDetail('insert', receivingDetail)}"
immediate="true">
<p:confirm header="Confirmation"
message="Do you wish to remove the selected detail?"
icon="ui-icon-alert" />
</p:commandButton>
</p:column>
</p:dataTable>
The backend code of adding a new row and deleting a row:
public void insertDetail(String owner) {
ReceivingDetail receivingDetail = new ReceivingDetail();
receivingDetail.setReceiving(receiving);
receivingDetail.setQtyStored(new BigDecimal("0.00"));
receiving.getReceivingDetails().add(receivingDetail);
RequestContext context = RequestContext.getCurrentInstance();
if (owner.equals(OWNER_INSERT)) {
context.update("insertForm");
context.execute("PF('insertDialogWV').show();");
} else if (owner.equals(OWNER_UPDATE)) {
context.update("updateForm");
context.execute("PF('updateDialogWV').show();");
}
}
public void deleteDetail(String owner, ReceivingDetail receivingDetail) {
receiving.getReceivingDetails().remove(receivingDetail);
ItemService itemSvc = (ItemService) getService(ItemService.class);
setItems(itemSvc.find());
RequestContext context = RequestContext.getCurrentInstance();
if (owner.equals(OWNER_INSERT)) {
context.update("insertForm");
context.execute("PF('insertDialogWV').show();");
} else if (owner.equals(OWNER_UPDATE)) {
context.update("updateForm");
context.execute("PF('updateDialogWV').show();");
}
}
Any idea what went wrong with my code?
I am using Primefaces 5 and JSF 2.2.
This is the first time I posting a question, not sure did I do it right, let me know if I need to correct anything, thanks in advance.
Edited:
Just in case this information is required, the datatable resides within a dialog as such.
<h:form id="insertForm">
<p:dialog id="insertDialog" widgetVar="insertDialogWV" modal="true"
draggable="false" resizable="false" header="Add Record"
closable="false">
</p:dialog>
</h:form>
Removed immediate="true" in the command button and it works, the table select and show the value according to the backend bean properly.
I am using Primefaces 3.5 with Weblogic 11. I have a page where a dialog to edit a 'profile' entity ('perfil' in Portuguese) which is called from two places. First from a commandButton to insert a new profile. The second from a dataTable to edit a specific profile. Below, I show the code:
Snippet of XHTML page
<p:fieldset legend="Pesquisa de Perfil">
<p:panelGrid columns="2">
<f:facet name="footer">
<p:commandButton id="btnPesquisar"
actionListener="#{perfilAcessoMB.pesquisar}" value="Pesquisar"
immediate="true" update="pnlPerfis" styleClass="ui-icon-search" />
<p:spacer width="20"></p:spacer>
<!-- OPEN DIALOG TO CREATE A NEW PROFILE -->
<p:commandButton id="btnIncluir" value="Incluir"
update="dlgPerfil" immediate="true"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao(null)}"
oncomplete="dlgPerfil.show();">
</p:commandButton>
</f:facet>
</p:panelGrid>
</p:fieldset>
<br />
<p:outputPanel id="pnlPerfis" layout="block">
<p:fieldset id="resultadoPesquisa" legend="Resultado da Pesquisa"
rendered="#{not empty perfilAcessoMB.perfis}">
<p:dataTable id="tblPerfis" value="#{perfilAcessoMB.perfis}"
var="perfil" emptyMessage="Nenhum perfil encontrado.">
<p:column headerText="Nome do Perfil">
<h:outputText value="#{perfil.nome}"></h:outputText>
</p:column>
<p:column headerText="Descrição do Perfil">
<h:outputText value="#{perfil.descricao}"></h:outputText>
</p:column>
<p:column headerText="Situação do Perfil"
style="text-align: center; width: 100px;">
<h:outputText value="Ativo" rendered="#{perfil.situacao}" />
<h:outputText value="Inativo" rendered="#{not perfil.situacao}" />
</p:column>
<p:column headerText="Editar"
style="text-align: center; width: 50px;">
<!-- OPEN DIALOG TO EDIT A NEW PROFILE -->
<p:commandLink id="lnkEditar" immediate="true"
title="Editar Perfil" update=":formPrincipal:dlgPerfil :formPrincipal:pnlPerfilEdicao"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao(perfil)}"
oncomplete="dlgPerfil.show();">
<h:outputText value="Editar" />
</p:commandLink>
</p:column>
<p:column headerText="Excluir"
style="text-align: center; width: 50px;">
</p:column>
</p:dataTable>
</p:fieldset>
</p:outputPanel>
<p:dialog id="dlgPerfil" widgetVar="dlgPerfil" resizable="false"
closable="true" modal="true" closeOnEscape="true"
header="#{(empty perfilAcessoMB.perfil)? 'Incluir': 'Editar'} Perfil">
<h:outputText value="#{perfilAcessoMB.perfil}"></h:outputText>
<h:panelGroup id="pnlPerfilEdicao" layout="block">
<p:fieldset legend="Dados do Perfil">
<p:panelGrid columns="2">
<h:outputLabel id="lblNomePerfilEdicao" value="Nome do Perfil"
for="txtNomePerfilEdicao" />
<p:inputText id="txtNomePerfilEdicao" required="true"
requiredMessage="É obrigatório preencher o campo Nome do Perfil."
value="#{perfilAcessoMB.perfil.nome}" maxlength="20" size="20"></p:inputText>
<h:outputLabel id="lblDescricaoPerfilEdicao"
value="Descrição do Perfil" for="txtDescricaoPerfilEdicao" />
<p:inputText id="txtDescricaoPerfilEdicao" required="true"
requiredMessage="É obrigatório preencher o campo Descrição do Perfil."
value="#{perfilAcessoMB.perfil.descricao}" maxlength="20"
size="20"></p:inputText>
<h:outputLabel id="lblSituacaoPerfilEdicao" value="Situação"
for="selSituacaoPerfilEdicao" />
<p:selectOneMenu id="selSituacaoPerfilEdicao"
value="#{perfilAcessoMB.perfil.situacao}">
<f:selectItems value="#{perfilAcessoMB.situacoesEdicao}" />
</p:selectOneMenu>
</p:panelGrid>
</p:fieldset>
<br />
<p:fieldset legend="Permissões">
<p:pickList id="pickFuncoes" value="#{perfilAcessoMB.funcoes}"
var="funcao" itemValue="#{funcao}"
itemLabel="#{funcao.descricao}" required="true"
requiredMessage="É obrigatório associar ao menos uma funcionalidade ao perfil."
converter="funcaoConverter" />
<p:column>#{funcao.descricao}</p:column>
</p:fieldset>
<p:panelGrid columns="2">
<p:commandButton id="btnSalvarPerfil" value="Salvar"
actionListener="#{perfilAcessoMB.salvar}"
oncomplete="if(args && !args.validationFailed) dlgPerfil.hide();" />
<p:commandButton id="btnCancelarPerfil" value="Cancelar"
immediate="true" onclick="dlgPerfil.hide();" />
</p:panelGrid>
</h:panelGroup>
</p:dialog>
MangedBean (perfilAcessoMB)
#ManagedBean
#ViewScoped
public class PerfilAcessoMB extends BaseMB {
private PerfilAcessoORM perfil;
private List<PerfilAcessoORM> perfis;
private String nomePerfil;
private Boolean situacao;
private DualListModel<FuncaoORM> funcoes;
private SelectItem[] situacoesPesquisa = new SelectItem[] {
new SelectItem(null, "Todos"), SELECT_ITEM_ATIVO,
SELECT_ITEM_INATIVO };
private SelectItem[] situacoesEdicao = new SelectItem[] {
SELECT_ITEM_ATIVO, SELECT_ITEM_INATIVO };
private FuncaoORM funcaoA = new FuncaoORM(1L, "FUNÇÃO A"), //
funcaoB = new FuncaoORM(2L, "B Function"), //
funcaoC = new FuncaoORM(10L, "Se Funssaum");
public void abrirDialogoEdicao(PerfilAcessoORM p) {
this.perfil = (p == null)? new PerfilAcessoORM(): p;
System.out.println("PerfilAcessoMB.onAbrirDialogoEdicao(): "
+ this.perfil);
List<FuncaoORM> funcoesDisponiveis = new ArrayList<FuncaoORM>(
Arrays.asList(funcaoA, funcaoB, funcaoC));
// Remove from funcoesDisponiveis those whose are present in perfil.
if (this.perfil.getFuncoes() == null) {
this.funcoes = new DualListModel<FuncaoORM>(funcoesDisponiveis,
Lists.<FuncaoORM> newArrayList());
} else {
funcoesDisponiveis.removeAll(this.perfil.getFuncoes());
this.funcoes = new DualListModel<FuncaoORM>(funcoesDisponiveis,
this.perfil.getFuncoes());
}
}
// Getters & Setters
}
PerfilAcessoORM (Profile) Entity
public class PerfilAcessoORM {
private Long id;
private String nome;
private String descricao;
private Boolean situacao = null;
private List<FuncaoORM> funcoes;
// Getters & Setters
}
FuncaoORM Entity:
public class FuncaoORM {
private Long id;
public String descricao;
// Getters & Setters
}
What is my problem? Apparently, when I want insert a new Profile, all seems OK. However, when I click to edit an existent profile to open the dialog, although the outputText and pickList are correctly filled, the inputText's and selectOneMenu are not.
Looking for solutions, I found here a suggestion to use appendToBody="true" in dialog. When I tried, the inputText's and selectOneMenu are correctly filled. However, the validation is not working as waited. When I click to save it is showed a message indicating that pickList is not filled, even if it is really filled. Actually, even if inputText's are not filled, there is no message about these inputTexts although they are required.
Another alternative would be use <f:setPropertyActionListener> inside commandLink:
<!-- OPEN DIALOG TO CREATE A NEW PROFILE -->
<p:commandButton id="btnIncluir" value="Incluir"
update="dlgPerfil" immediate="true"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao}"
oncomplete="dlgPerfil.show();">
<f:setPropertyActionListener target="#{perfilAcessoMB.perfil}" value="#{null}"/>
</p:commandButton>
<!-- OPEN DIALOG TO EDIT A NEW PROFILE -->
<p:commandLink id="lnkEditar" immediate="true"
title="Editar Perfil" update=":formPrincipal:dlgPerfil :formPrincipal:pnlPerfilEdicao"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao}"
oncomplete="dlgPerfil.show();">
<f:setPropertyActionListener target="#{perfilAcessoMB.perfil}" value="#{perfil}"/>
<h:outputText value="Editar" />
</p:commandLink>
The actionListener method would changed to:
public void abrirDialogoEdicao() {
if(this.perfil == null) {
this.perfil = new PerfilAcessoORM();
}
System.out.println("PerfilAcessoMB.onAbrirDialogoEdicao(): "
+ this.perfil);
// The rest remains the same ...
}
Now, when I click to create a new perfil, although in actionListener method the perfil attribute is filled, I got a NullPointerException when the dialog is renderized. It is like first is called perfilAcessoMB.setPerfil(), after the dialog is opened and finally actionListener method. On the other hand, if I click to edit an existent profile, I return to initial situation.
Therefore, I am lost, without idea how to solve this issue.
Thanks,
Rafael Afonso
The solution was incredible simple: just added process="#this" to both commandButtons.
<!-- OPEN DIALOG TO EDIT A NEW PROFILE -->
<p:commandLink id="lnkEditar" immediate="true"
title="#{msg['titulo.edicao']}" process="#this"
update=":formPrincipal:dlgPerfil"
actionListener="#{perfilAcessoMB.abrirDialogoEdicao(perfil)}"
oncomplete="dlgPerfil.show();">
<h:outputText value="#{msg['titulo.edicao']}" />
</p:commandLink>
I am getting a null selected row when I press the showDialog command button
I can't see what is my problem
This is my first form:
<h:form id="firstForm">
<p:commandButton action="#{testBB.showDialog}" id="showDialog"
update=":secondForm" value="#{msg['show.dialog']}" />
</h:form>
This is my second form:
<h:form id="secondForm">
<p:dataTable id="testDatatable"
rendered="#{not empty testBB.list}"
rowKey="#{order.orderNumber}"
selection="#{testBB.selectedRow}"
selectionMode="single"
sortBy="customerName" value="#{testBB.list}" var="order">
<p:column headerText="#{msg['order.number']}">
<h:outputText value="#{order.orderNumber}" />
</p:column>
<p:column headerText="#{msg['total.value']}">
<h:outputText value="#{order.totalValue}" />
</p:column>
</p:dataTable>
</h:form>
My backing bean:
#ManagedBean
#ViewScoped
public class TestBB implements Serializable {
private List<Order> list;
private Order selectedRow;
public void showOrder() {
try {
System.out.println(selectedRow);
} catch (Exception exception) {
}
}
}
And my DTO:
public class Order implements Serializable {
private int orderNumber;
private double totalValue;
public void showOrder() {
try {
System.out.println(selectedRow);
} catch (Exception exception) {
}
}
/** Getters and setters */
}
What is wrong in my code?
Put
<p:ajax event="rowSelect" />
<p:ajax event="rowUnselect" />
inside your datatable for selection/unselection to happen as soon as click happens.
If you need selection only on button click use 'process' like this
<p:commandButton process=":secondForm:testDatatable" update=":secondForm"/>
You need to update the model on rowSelection. This can be done using a <p:ajax event="rowSelect" />. Here is how I think your Datatable should look like:
<p:dataTable id="testDatatable"
rendered="#{not empty testBB.list}"
rowKey="#{order.orderNumber}"
selection="#{testBB.selectedRow}"
selectionMode="single"
sortBy="customerName" value="#{testBB.list}" var="order">
<p:ajax event="rowSelect" />
<p:column headerText="#{msg['order.number']}">
<h:outputText value="#{order.orderNumber}" />
</p:column>
<p:column headerText="#{msg['total.value']}">
<h:outputText value="#{order.totalValue}" />
</p:column>
</p:dataTable>
A good example can be found here (Primefaces Demo).
As Kerem Baydogan suggested you have to include process attribute with your data table id in your command button.
If you are not including process attribute then no components will be processed in the component tree and no modal values will be updated hence you are getting selection as null.
I feel there is no need of updating data table if you are not changing its state.
I have a simple datatable with cell editing in primefaces. It works, but, first, does not create JavaScript message, second, it creates 15 identically queries to db. (i can see that in hibernate console)
Code is token from official site:
<h:form id="form">
<p:growl id="messages" showDetail="true"/>
<p:contextMenu for="clients" widgetVar="cMenu">
<p:menuitem value="Edit Cell" icon="ui-icon-search" onclick="clientsTable.showCellEditor();return false;"/>
<p:menuitem value="Hide Menu" icon="ui-icon-close" onclick="cMenu.hide()"/>
</p:contextMenu>
<p:dataTable id="clients" var="client" value="#{clientsBean.clients}" paginator="true" rows="5"
editable="true" editMode="cell" widgetVar="clientsTable">
<p:ajax event="cellEdit" listener="#{clientsBean.onCellEdit}" update=":form:messages"/>
<p:column headerText="Name" style="width:25%">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{client.name}"/></f:facet>
<f:facet name="input"><p:inputText id="nameInput" value="#{client.name}"
style="width:96%"/></f:facet>
</p:cellEditor>
</p:column>
So, when i edit some info and press Enter, it creates 15 queries and does not show JS message.
Bean's getClients() is a simple hibernate query (works fine), and onCellEdit() looks like
public void onCellEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(newValue != null && !newValue.equals(oldValue)) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cell Changed", "Old: " + oldValue + ", New:" + newValue);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
Also new strange bug apperead : oldValue and newValue in that bean are always same.
I have a <p:dataTable> , with a checkbox on the last column. I want to color the rows of the table based on the status of the checkbox.
<p:dataTable var="acs" value="#{myBean.listaRevogaveis}"
emptyMessage="#{rotulo.mensagemSemDados}" paginator="true"
rows="10" id="tableacs"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}">
<p:column headerText="Nome" sortBy="#{acs.nome}"
filterBy="#{acs.nome}">
<h:outputText value="#{acs.nome}" />
</p:column>
<p:column headerText="Address" sortBy="#{acs.address}" filterMatchMode="contains"
filterBy="#{acs.address}" filterMaxLength="8">
<h:outputText value="#{acs.address}" />
</p:column>
<p:column headerText="Perfil" sortBy="#{acs.cdPerfil}"
filterBy="#{acs.cdPerfil}" filterMaxLength="2">
<h:outputText value="#{acs.cdPerfil}" />
</p:column>
<p:column headerText="Cadastramento">
<h:outputText value="#{acs.tsSolicitacao}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</p:column>
<p:column headerText="Concedido">
<h:outputText value="#{acs.concedidoPor}" />
</p:column>
<p:column headerText="Revogar">
<p:selectBooleanCheckbox value="#{acs.ativo}" >
<p:ajax event="valueChange" oncomplete="toggleColor(this, #{acs.ativo}" listener="#{myBean.checkBox}" update="#form"/>
</p:selectBooleanCheckbox>
</p:column>
</p:dataTable>
So on the toggling of #{acs.ativo} I want that row to receive a different background color.
Following the answer of this question I tried to add this to my xhtml:
<style type="text/css">
.linhaDestacada { background-color: red !important;}
</style>
<script type="text/javascript">
function toggleColor(col, status) {
var linha = jQuery(col).parent();
if(status) {
linha.removeClass('linhaDestacada');
} else {
linha.addClass('linhaDestacada');
}
}
</script>
But that's of no use. I put some alerts to see if the function was being called, it is. However, trying to see the tagName, or any property of the linha variable returns null.
There is another interesting point, the callback is being called with the previous value of the checkbox. When box is checked, javascript toggleColor() is receiving false on the status, when its unchecked it receives true.
How can I make the row background toggle together with the checkbox toggle?
Ok, there were a TON of bugs and problems in that one.
First:
primefaces sets the background of the rows to a blank image (depending on the skin). you have to override the url() of the background, so the CSS should look like:
.linhaDestacada { background: url('') red !important;}
Second:
Calling the javascript from the ajax tag was causing the jQuery to find nulls (dunno why). move the callback to the checkbox tag, using its onchange attribute.
The final javascript fragment was:
<script type="text/javascript">
function toggleColor(col, status) {
var linha = jQuery(col).parent().parent().parent().parent().parent();
if(status) {
linha.removeClass('linhaDestacada');
//alert("remove " + linha.html());
} else {
linha.addClass('linhaDestacada');
//alert("add " + linha.html());
}
}
</script>
Third:
Updating the WHOLE form is a no-no (the css class you added with javascript was being erased)... you should update only what really matters (in this case, the checkbox and the command button.
<p:selectBooleanCheckbox value="#{acs.ativo}" onchange="toggleColor(this, #{acs.ativo})">
<p:ajax event="valueChange" listener="#{myBean.checkBox}" update="#this :formAcesso:btnRevogaNuke" />
</p:selectBooleanCheckbox>
Fourth:
the commandButton was not rendering. It would be updated on the ajax response, but the browser did not display it. Found this answer, and moved the id btnRevogaNuke on the encapsulating element:
<h:panelGroup id="btnRevogaNuke" layout="block">
<p:commandButton icon="ui-icon-alert" value="Confirmar rendered="#{myBean.confirmar()}" style="margin-left:600px;" action="#{acessoBean.revogaTodos()}" process="#this #form" update="#form" />
</h:panelGroup>