I need to close my messages dialog without using the built in close button. An embedded "CLOSE" button within the message needs to fire of a method in the backing bean, and when finished, the message box should close.
My code calls the actionListener, but I am unable to clear the message box on submission. In my last attempt, I tried to do it from the Backing Bean, but the box refuses to go away.
Below is sample test code.
<h:form id="form1">
<h:panelGroup id="myPanel" layout="block" class="scap-block"
rendered="#{not chartView.acknowledged}">
<p:messages id="banner" showSummary="true" showDetail="false"
autoUpdate="true" closable="true" escape="false">
</p:messages>
<p:commandButton widgetVar="acceptContinue"
style-class="align right" value="Close" type="ajax"
actionListener="#{chartView.close}" render="myPanel" />
</h:panelGroup>
</h:form>
<f:event type="preRenderView" listener="#{chartView.init}" />
</h:body>
Bean:
#ManagedBean(name = "chartView")
#ViewScoped
public class ChartView implements Serializable {
private boolean acknowledged = false;
public void init() {
log.debug("preRender init() method");
String detail = "PrimeFaces Rocks."
+"<button aria-disabled='false' id='form1:j_idt5' name='form1:j_idt5' "
+ "class='ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only' "
+ "onclick='PrimeFaces.ab({s:"form1:j_idt5"});return false;' type='ajax'>"
+ "<span class='ui-button-text ui-c'>Close</span></button>";
FacesContext.getCurrentInstance().addMessage("banner",
new FacesMessage(FacesMessage.SEVERITY_ERROR, detail, "Some details"));
}
public void close() {
System.err.println("Acknowledged");
log.debug("###Close called###");
setAcknowledged(true);
RequestContext context = RequestContext.getCurrentInstance();
context.update(":form1:myParent");
}
Related
My xhtml is split in to Menu area (defaultMenu.xhtml) and Content area (defaultContent.xhtml).
The code for defaultMenu.xhtml is:
<h:form id="defaultmenuform">
<p:outputPanel id="menupanel" class="contain auto-fixed-center">
<p:panel id="pmenu" visible="#{phController.user.menuVisible}">
<table id="stutable">
<tr>
<td width="15%">
<p:outputLabel id="stuname" value="#{phController.phBean.studentName}" />
</td>
<td>
<p:tabMenu activeIndex="#{param.selectedtab}">
<p:menuitem value="Home" outcome="phome" icon="ui-icon-star">
<f:param name="selectedtab" value="0" />
</p:menuitem>
<p:menuitem value="Bank" outcome="bhome" icon="ui-icon-person">
<f:param name="selectedtab" value="1" />
</p:menuitem>
</p:tabMenu>
</td>
</tr>
</table>
</p:panel>
</p:outputPanel>
</h:form>
The defaultContent.xhtml actually displays the ph.xhtml content (as part of functional navigation) and the code is:
<ui:define name="content">
<f:event listener="#{phController.readPeople}" type="preRenderView">
</f:event>
<h:form id="form">
<p:selectOneRadio id="selstud" value="#{phController.phBean.ssSeq}" layout="custom">
<p:ajax update=":defaultmenuform:parentmenupanel :defaultmenuform:stuname" listener="#{phController.onChangePerson}"/>
<f:selectItems value="#{phController.selectStudents}" />
</p:selectOneRadio>
<div style="width: 300px; float:left;">
<p:dataGrid var="studentlist" value="#{phController.listStudent}" columns="1" rowIndexVar="stuindex">
<p:panel header="" style="text-align:left">
<h:panelGrid columns="1" style="width:100%">
<h:outputText value="#{studentlist.studentName}" />
<p:radioButton for=":form:selstud" itemIndex="#{stuindex}"/> Select
</h:panelGrid>
</p:panel>
</p:dataGrid>
</div>
</h:form>
</ui:define>
The code for backing bean is:
Map<String, Object> studentparam = new HashMap<>();
studentparam.put("studentSeq", phBean.getSsSeq());
lS = getBaseDAOService().readStudent("readStudent", studentparam);
phBean.setStudentName(lS.get(0).getStudentFirstName() + " " + lS.get(0).getStudentLastName());
As you can see, I am calling the onChangeStu method to display the selected Student Name in defaultMenu.xhtml. I am using Custom Layout p:selectOneRadio in ph.xhtml and onClick trying to update a p:outputLabel in defaultMenu.xhtml.
The backing bean method gets invoked successfully and the value is also set in variable phController.phBean.studentName, but the update is not working. I also checked using view source and the id is “:defaultmenuform:stuname”, I also tried updating the menu panel ":defaultmenuform:menupanel”, but none of this works.
Not sure how to resolve this. Please suggest.
Including the structure of all .xhtmls
<h:body id="entirePageBody">
<div id="page">
<ui:insert name="header" >
<ui:include src="/template/defaultHeader.xhtml" />
</ui:insert>
<ui:insert name="menu" >
<ui:include src="/template/defaultMenu.xhtml" />
</ui:insert>
<div id="content_div" class="auto-fixed-center">
<div id="content_div_padding" class="content-block">
<ui:insert name="content" >
<ui:include src="/template/defaultContent.xhtml" />
<ui:debug hotkey="z" />
</ui:insert>
</div>
</div>
<ui:insert name="footer" >
<ui:include src="/template/defaultFooter.xhtml" />
</ui:insert>
</div>
</h:body>
PhController.java:
public class PhController extends BaseController implements Serializable {
private List<Stud> listStudent;
private List selectStudents;
SelectItem option;
private PhBean phBean;
private Boolean menuVisible;
int counter = 0;
public PhController() {
phBean = new PhBean();
}
public void readPeople() {
listStudent = new ArrayList<Stud>();
listStudent.add(new Stud(1, "John Miller"));
listStudent.add(new Stud(2, "Scott Jackson"));
selectStudents = new ArrayList();
option = new SelectItem(listStudent.get(0).getStudentSeq(), "Select");
selectStudents.add(option);
option = new SelectItem(listStudent.get(1).getStudentSeq(), "Select");
selectStudents.add(option);
phBean.setSsSeq(String.valueOf(1));
phBean.setSelectedName(listStudent.get(0).getStudentName());
menuVisible = true;
}
public void onChangePerson() {
phBean.setSelectedName(listStudent.get(1).getStudentName());
}
// Getters and Setters
}
PhBean.java:
public class PhBean implements Serializable {
private String ssSeq;
private String studName; // Used to display the name in the Menu bar.
private String selectedName;
public PhBean() {
}
// Getters and Setters
}
I'd say that in the p:ajax in defaultContent.xhtml the list of components to be updated should be separated with spaces only, no commas - so try changing this:
update=":defaultmenuform:menupanel, :defaultmenuform:stuname"
to this:
update=":defaultmenuform:menupanel :defaultmenuform:stuname"
UPDATE
I played with this a bit more and may have found a clue - please add the following code to defaultmenuform:
<p:messages autoUpdate="true" showDetail="true" />
This should help us tracking the reason for failed validation (in case failing validation is the root cause for you - as I said, I have rather limited possibility to reproduce this issue).
Anyway, when I selected some item in p:selectOneRadio, an error message like this appeared:
Conversion Error setting value 'test001.Student#4110c95c' for 'null Converter'.
And the root cause was on this row:
<p:selectOneRadio id="selstud" value="#{phController.phBean.ssSeq}" layout="custom">
p:selectOneRadio expects only String to be passed as a value - and ssSeq is very likely of a different type. Try to change the way value is populated to ensure it is always String - maybe a different attribute of the phBean or simply a brand new String one.
NOTE: if this doesn't help, maybe you could update your question with very simplified example of how phController and phBean could look like if we are to test it.
UPDATE #2
So you have explained there is a problem that you want to call phController.readPeople every time the page is loaded/refreshed, but instead it gets loaded with each and every Ajax request, thus overwriting the values.
In your PhController (it is a bean, right? session scoped?) you could add something like this (omitted null checks for the sake of readability):
public void readPeopleOnGet() {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
HttpServletRequest req = (HttpServletRequest) ec.getRequest();
String reqMethod = req.getMethod();
if ("GET".equals(reqMethod)) {
readPeople();
}
}
With the above method you could keep this part of your defaultContext.xhtml in place, provided it is actually called (I assume so), just with the listener method changed:
<f:event listener="#{phController.readPeopleOnGet}" type="preRenderView">
</f:event>
The method readPeopleOnGet will still be called with every request to the page, but since Ajax requests are POST, it will only call readPeople when the page is loaded or refreshed as whole.
This may not be a "perfectly clean" solution, but seemed to work properly when I tested it.
UPDATE #3
Well, since you use PrimeFaces, it would be possible to identify Ajax call also this way:
public void readPeopleOnGet() {
RequestContext rc = RequestContext.getCurrentInstance();
if (!rc.isAjaxRequest()) {
readPeople();
}
}
But if I got your point from latest comments, you want to only run readPeople when the page is loaded for the very first time - so the following part could be even better for that.
You didn't answer if PhController is actually a bean, but I assume it is (there were no annotations visible from the code you posted). You may try making it #SessionScoped:
#ManagedBean
#SessionScoped
public class PhController extends BaseController implements Serializable {
// the rest of the PhController goes here...
Then you could add something like this to the PhController:
#PostConstruct
private void init() {
readPeople();
}
The annotation #PostConstruct ensures the method init is called exactly once after the bean was created. You can continue calling the method readPeople from other places as necessary, while removing both the <f:event ... /> and readPeopleOnGet as these will no longer be needed.
I just started learning JSF and PrimeFaces, and I'm having a hard time trying to get PrimeFaces' datatable to work. I have a checkbox-based selection mechanism (more than one row can be selected at the same time), so that clicking on the "Delete selected users" button triggers a method call to the backing bean to delete the corresponding users from the database.
The problem is that the selected rows are not stored in the backing bean's selectedUsers array, and I can't understand why, since my code is exactly the same as the one hosted on PrimeFaces' ShowCase. As a consequence, the button successfully triggers the confirmation dialog, but no user ever gets deleted from the system. Does anyone have any advice?
Thank you in advance!
xhtml file
<h:form id="tableForm">
<p:dataTable id="userList" var="user" value="#{userListBean.userList}"
selection="#{userListBean.selectedUsers}" rowKey="#{user.username}">
<f:facet name="header">User list</f:facet>
<p:column selectionMode="multiple" style="width:2%"/>
<!-- data columns here, working just fine -->
<f:facet name="footer">
<p:commandButton value="Delete selected users" icon="ui-icon-trash" action="#{userListBean.deleteSelectedUsers()}">
<p:confirm header="Deletion confirmation" message="Are you sure you want to delete #{fn:length(userListBean.selectedUsers)} users?" icon="ui-icon-alert" />
</p:commandButton>
Registered users: #{fn:length(userListBean.userList)}
</f:facet>
</p:dataTable>
<p:confirmDialog global="true" showEffect="fade">
<p:commandButton value="Yes" type="button" styleClass="ui-confirmdialog-yes" icon="ui-icon-check" />
<p:commandButton value="No" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
</p:confirmDialog>
</h:form>
Backing Bean
(userMgr handles persistence on the server, it should have nothing to do with my issue)
#ManagedBean(name="userListBean")
#ViewScoped
public class UserListBean {
#EJB
private UserManager userMgr;
private List<UserDTO> userList;
private UserDTO[] selectedUsers;
public UserListBean() {
}
public void deleteSelectedUsers() {
for(UserDTO u : selectedUsers)
userMgr.deleteUser(u.getUsername());
setUserList(userMgr.retrieveAllUsersDTO());
}
public List<UserDTO> getUserList() {
if(userList == null)
setUserList(userMgr.retrieveAllUsersDTO());
return userList;
}
public void setUserList(List<UserDTO> userList) {
this.userList = userList;
}
public List<UserDTO> retrieveUserList() {
return userMgr.retrieveAllUsersDTO();
}
public UserDTO[] getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(UserDTO[] selectedUsers) {
this.selectedUsers = selectedUsers;
}
}
(As a side question: the #{fn:length(userListBean.selectedUsers)} EL expression always returns 0. I used to think it was because of the broken selection mechanism, but could it be because the array is still empty when the confirmation dialog is rendered?)
You need to activate event rowSelect by adding <p:ajax event="rowSelect"/> to dataTable.
I have this code :
Add.xhtml :
<h:form id="nouv">
<h:panelGrid columns="2">
<h:outputText value="Nom:"></h:outputText>
<p:inputText value="#{ddeBean.nom}"></p:inputText>
<p:commandButton id="save"
value="ajouter"
update=":nouv:btn"
actionListener="#{ddeBean.ajouter}">
</p:commandButton>
<p:outputPanel id="btn">
<h:outputText rendered="#{ddeBean.created}" value="#{ddeBean.message}"/>
<p:commandButton id="btn_cr" value="add" rendered="#{ddeBean.created}"
action="pool.xhtml?faces-redirect=true">
</p:commandButton>
</p:outputPanel>
</h:panelGrid>
</h:form>
ddeBean.java :
#ManagedBean(name = "ddeBean")
#RequestScoped
public class DemandeBean implements Serializable{
ddeDAO dao = new ddeDaoImpl();
private String nom;
public String message = "";
private boolean created = false;
public void test(ActionEvent event){
Demande p = new Demande();
p.setDde(this.nom);
dao.Nouveau_dde(p);
created = true;
this.setMessage("saved!");
}
}
When I click commandButton Ajouter the message an the commandbutton Add will be shown, but commandbutton Add doesn't redirect to pool.xhtml.
When you click on the button Add, the bean is recreated and the value #{ddeBean.created} then reinitialized to false so the button doesn't get rendered before action take place.
To fix that, you need to change the scope of your bean to #ViewScoped.
You should also make sure to replace
public void test(ActionEvent event){
by
public void ajouter(ActionEvent event){
if you want that your button work properly.
Another solution
Since you are using PrimeFaces, you could show your button by JavaScript :
<p:commandButton id="save"
value="ajouter"
oncomplete="panel-create.show();"
actionListener="#{ddeBean.ajouter}">
</p:commandButton>
<p:outputPanel id="btn" style="display: none;" widgetVar="panel-create">
<h:outputText value="#{ddeBean.message}"/>
<p:commandButton id="btn_cr" value="add"
action="pool.xhtml?faces-redirect=true">
</p:commandButton>
</p:outputPanel>
Note the oncomplete attribute on the p:commandButton, the widgetVar attribute on the p:panel and the rendered attributes removed.
I have the main page with includes testcomponent1 which inturn includes testcomponent2. Ajax call is in testcomponent2. The call is intiated in the javascript but never hits the controller. If the ajax call is moved into testcomponent1, it triggers the call and makes it to the controller. I am including the test code for your reference.
TESTCONTROLLER:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.AjaxBehaviorEvent;
#ManagedBean
#ViewScoped
public class TestController implements Serializable {
/** <code>serialVersionUID</code> */
private static final long serialVersionUID = -999213365169849345L;
private int customerkey;
private String customerName;
public void processKeyChange(AjaxBehaviorEvent e){
System.out.println("I am in the Ajax method and my value is: " + customerkey);
}
//GETTERS AND SETTERS
public int getCustomerkey() {
return customerkey;
}
public void setCustomerkey(int customerkey) {
this.customerkey = customerkey;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
testPage.xhtml
<ui:define name="searchCriteria">
<h:form id="orderHeaderForm" prependId="false">
<h:panelGroup id="orderDiv" layout="block">
<com:testcomponent1 id="testComponent1"
customerKey="#{testController.customerkey}"
customerName="#{testController.customerName}"/>
</h:panelGroup>
</h:form>
</ui:define>
</ui:composition>
testcomponent1.xhtml
<cc:interface>
<cc:attribute name="customerKey" type="java.lang.Integer" />
<cc:attribute name="customerName" type="java.lang.String" />
</cc:interface>
<cc:implementation>
<h:panelGroup id="#{cc.clientId}" layout="block">
<com:testcomponent2 id="testcomponent2"
key="#{cc.attrs.customerKey}"
name="#{cc.attrs.customerName}" />
</h:panelGroup>
</cc:implementation>
testcomponent2.xhtml
<cc:implementation>
<h:panelGrid id="#{cc.clientId}" columns="2" border="0" cellspacing="0" cellpadding="0">
<h:outputLabel id="customerid" for="txtcustomerKey"/>
<h:inputText id="txtcustomerKey" value="#{cc.attrs.key}" onchange="alert (document.getElementById(this.id).value)">
<f:ajax event="change" listener="#{testController.processKeyChange}" execute="#this" render="txtCustomerName" />
</h:inputText>
<h:outputLabel id="customerName" for="txtCustomerName"/>
<h:outputText value="#{cc.attrs.name}" id="txtCustomerName" />
</h:panelGrid>
</cc:implementation>
thanks
I think the problem is in <h:panelGrid id="#{cc.clientId}"...>. By default, a composite component is an instance of UINamingContainer, so instead do that, you can set an id with any name and use it. A good practice is avoid EL expressions in id field.
You shouldn't reassign #{cc.clientId} as ID of JSF components, but instead as ID of plain vanilla HTML elements such as <span> or <div>.
<span id="#{cc.clientId}">
or
<div id="#{cc.clientId}">
I have following sample code.
Initially, only commandButton Two is visible. When I click this button, commandButton One is also visible. But when I click One, the backing-bean method click1 does not get fired.
Following is my code:
xhtml
<h:form id="form1">
<h:inputHidden id="show" value="#{bean.show1}" />
<h:commandButton id="button1" value="One" action="#{bean.click1}"
rendered="#{bean.show1}" />
</h:form>
<h:form id="form2">
<h:inputHidden id="show" value="#{bean.show1}" />
<h:commandButton id="button2" value="Two" action="#{bean.click2}" />
</h:form>
backing-bean
#RequestScoped
#Named("bean")
public class JsfTrial implements Serializable {
private static final long serialVersionUID = 2784462583813130092L;
private boolean show1; // + getter, setter
public String click1() {
System.out.println("Click1()");
return null;
}
public String click2() {
System.out.println("Click2()");
setShow1(true);
return null;
}
}
I found a very informative answer by BalusC.
h:commandLink / h:commandButton is not being invoked
If I understand it correctly, my problem is due to point 5 of this answer.
Does that also mean we can not use hidden commandButton with #RequestScoped backing-bean?
You can use the request scope, you should only pass the condition as a request parameter to the subsequent requests by <f:param> instead of by a JSF hidden input field <h:inputHidden>. The value of the hidden input field is only set in the model during Update Model Values phase, while the condition of the rendered attribute is already evaluated during Apply Request Values phase which is earlier.
So, use <f:param> instead of <h:inputHidden>:
<h:form id="form1">
<h:commandButton id="button1" value="One" action="#{bean.click1}"
rendered="#{bean.show1}">
<f:param name="show1" value="#{bean.show1}" />
</h:commandButton>
</h:form>
<h:form id="form2">
<h:commandButton id="button2" value="Two" action="#{bean.click2}">
<f:param name="show1" value="#{bean.show1}" />
</h:commandButton>
</h:form>
This way you can extract them as request parameter in bean's (post)constructor.
public JsfTrial() {
String show1 = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("show1");
this.show1 = (show1 != null) && Boolean.valueOf(show1);
}
Ugly, but CDI doesn't offer a builtin annotation which substituties JSF's #ManagedProperty("#{param.show1}"). You could however homegrow such an annotation.