I have a JSF MyFaces dataTable that contains a list of elements and a column with a delete button. All I want to do is to popup a dialog when clicking on the delete button that would allow the user to confirm or cancel the operation.
I already have the dialog (reduced for simplicity and using <a> because of the lack of HTML5 support):
<div id="myModal">
<h:form>
<a data-dismiss="modal">Close</a>
<h:commandLink action="#{somethingMagicInHere?}">Confirm</h:commandLink>
</h:form>
</div>
In the dataTable I have something like this (also simplified):
<h:dataTable id="myDataTable" value="#{bean.elementList}" var="element">
<h:column>
<f:facet name="header">Actions</f:facet>
<a class="call-modal">Delete</a>
</h:column>
</h:dataTable>
Finally my ManagedBean looks like this:
#ManagedBean(name = "bean")
#RequestScoped
public class ElementClassBean {
...
public String actionToPerform(ElementClass e) {
MyBusinessLogicModel.getInstance().deleteElement(e);
}
}
So, in short, jQuery executes when loading the page and takes all elements with class call-modal and sets an onclick to them so that they display the component with id myModal, which is of course the modal window. I inherited this working this way and prefer not change it but any solution or ideas will help.
I can use a commandLink directly in the dataTable that would access actionToPerform(element) from the view but that, of course, won't fire the modal. So the main issue I see, given this structure, is how can I send the element being iterated in the dataTable to the modal once the Delete button is clicked? (I don't mind if the solution uses Ajax).
Any input will be helpful. Thanks.
Ok, this is the ugly but working solution that doesn't require me to refactor all the views and managed beans. In short: I added a hidden input field that would store the id of the element to delete in the modal form. In the datatable all I do is setting the value of the hidden input field once the button is clicked and fire the modal. The modal is then filled with the just updated value.
My simplified modal:
<div id="myModal">
<h:form id="myForm">
<h:inputHidden value="#{bean.elementIdInModal}" id="elementIdInModal"/>
<a data-dismiss="modal">Close</a>
<h:commandLink action="#{bean[actionToPerform]}">Confirm</h:commandLink>
</h:form>
</div>
My simplified dataTable:
<h:dataTable id="myDataTable" value="#{bean.elementList}" var="element">
<h:column>
<f:facet name="header">Actions</f:facet>
<h:link styleClass="call-modal"
onclick="$('#myForm\\:elementIdInModal').val(#{element.id})">
Delete
</h:link>
</h:column>
</h:dataTable>
My simplified ManagedBean:
#ManagedBean(name = "bean")
#RequestScoped
public class ElementClassBean {
private long elementIdInModal; // Ommiting getters and setters
public void actionToPerform() {
MyBusinessLogicModel.getInstance().deleteElement(elementIdInModal);
}
}
Related
I got a HtmlDatatable with
One CommandButton to Edit.
One CommandButton to Save.
One InputText to display info.
<h:form>
<h:dataTable var="entity" value="#{bean.entities}">
<h:column>
<f:facet name="header">ColumnA</f:facet>
<h:commandButton value="edit" actionListenner="#{bean.edit()}" />
<hcommandButton value="save" actionListenner="#{bean.save(entity)} rendered="false"/>
<h:inputText value="#{entity.value}"/>
</h:column>
</h:dataTable>
</h:form>
I would like when i click the CommandButton edit that the CommandButton save appear. How can i access the CommandButton save inside my method edit() from the bean ?
Is the ONLY WAY to do it is to pass the clientId from the button.
Or Is there ANOTHER WAY by passing the object itself instead as parameter of the EL and work with it in the method directly ? #{bean.edit(buttonSave)}
public void edit()
{
//TODO get the button save from the same row as the button triggered.
//TODO switch rendered to true.
}
Dont try to access your CommandButton save inside the edit() method. Add a boolean attriubte called something like editMode to your entity and try passing your entity to your edit method like this
<h:commandButton value="edit" actionListenner="#{bean.edit(entity)}" />
Now in your edit() method, add your entity as param and enable the edit mode on your entity
public void edit(Entity entity)
{
entity.setEditMode(true);
}
It is now possible with EL to make the rendered attribute of your commandButton to check the editMode of your entity like this
<h:commandButton value="edit" actionListenner="#{bean.edit(entity)}" rendered="#{!entity.editMode}"/>
<h:commandButton value="save" actionListenner="#{bean.save(entity)}" rendered="#{entity.editMode}"/>
So if the editMode attribute is true, you now should see the save button. The same way you can hide your edit button
My screen looks like this
The problem is that, when I press the Reset Button, the Code input field does not clear, as it was supposed to.
The jsf is the following:
<h:form id="form1">
<h:inputText id="code" value="#{MyBean.data.code}" />
<a4j:commandButton immediate="true"
action="#{MyBean.clear}" render="form1" update="#form">
</a4j:commandButton>
<h:outputText value="#{session.lastAccessedTime}">
<f:convertDateTime pattern="HH:mm:ss.SSS" type="date" />
</h:outputText>
</h:form>
The bean code is the following:
public class MyBean {
DataInnerClass data = new DataInnerClass();
//getter and setter for data
public class DataInnerClass {
private String code;
//getter and setter for code
public DataInnerClass() {
super();
}
}
public void clear() {
data = new DataInnerClass();
Logger.getLogger( MyBean.class.getName() ).log(Level.SEVERE, "data.code="+data.code);
//logs data.code=null
}
}
When I press the Reset button, the log shows that the value of the field code has become null (its no longer 'ZZ'); i also know that the screen refreshes successfully, because i have displayed the current time, which updates after every click. So the backing bean property changes, the screen refreshes, and still the input field keeps the same value. Do you have any idea why this is happening?
I found useful BalusC's answer on: How can I populate a text field using PrimeFaces AJAX after validation errors occur?
I understand from there that, in the case of some validation error, the input field will keep the value entered by the user, and will be out of sync with the backing bean. I must emphasize that in my case, there were no validation errors, but still, adding an <f:ajax resetValues> to the commandButton worked for me.
A concrete example of the resetValues attribute is on https://jsflive.wordpress.com/2013/06/20/jsf-22-reset-values/
Finally, my button tag looks like this:
<a4j:commandButton immediate="true"
action="#{MyBean.clear}" render="form1" update="#form">
<f:ajax render="code" resetValues="true" />
</a4j:commandButton>
I have a JSF application in wich i'm using ui:composition/ui:include to display some elements inside a page like in the following code
template.xhtml
...
<h:body>
...
<h:panelGroup id="mainPanel">
<ui:include src="#{myBean.page}"/>
</h:panelGroup>
...
</h:body>
items-list.xhtml
<ui:composition>
...
<h:form>
<p:dataTable var="item" value="#{myBean.items}">
<p:column>
<h:commandLink action="#{myBean.loadItemDetail(item)}"
process="#this"
update="mainPanel">
<h:outputText value="#{item.name}"/>
</h:commandLink>
</p:column>
</p:dataTable>
</h:form>
...
</ui:composition>
items-detail.xhtml
<ui:composition>
<h:form>
<!-- Some code to display and modify the item details-->
</h:form>
<ui:composition>
MyBean.java
#ManagedBean
#ViewScoped
public class MyBean {
private String page;
private List<Item> items;
private ItemDetail itmDetail;
#PostConstruct
private void init() {
page = "items-list.xhtml"
items = ... //some logic to populate the items list
}
public void loadItemDetail(Item item){
itmDetail = ... //some logic to get the item's detail
page = "item-detail.xhtml"
}
}
The first time I click on an item to see the details it works fine but after that, if I click on the browser's back button and try to load a different item details it keeps showing me the details of the first item.
I check the JSF lifeCycle for each call and although in every call the application goes through all the satages, only the first one calls the bean method locadItemDetail. is there a reason why my method is being ignored after the first success call? is there some kind of cache on JSF where my data is bean taken from instead of my Bean?
Also i tried to avoid this behavior implementing a filter as is suggest in this post and it kind of works but now when I click browser's back button it show me an annoying page preventing me from resend the form; is there a way to prevent that?
Note:
I know that i could change the app to use GET method instead of POST to avoid this cache problem but it will required some serious changes over the app so that's not an option.
Any help or guidance about why could this be happening will be appreciated.
I have a JSF 2 application that has two pages, one to list students and one to show details of a given student. The listing page has a link to the details page in each row of the students table, that opens a new tab in browser to show those details, when clicked.
Now the requirements changed to no more show details in a new tab, but in a modal dialog in the listing page.
My idea is to simply embed the details page content in the modal dialog so the listing page will not get too big and hard to maintain. Here start my doubts. After some research I changed the link in each row of the listing to the following button:
<p:commandButton value="Details" type="button"
onclick="PF('dialog-details').show()">
</p:commandButton>
The dialog is declared as follows:
<p:dialog widgetVar="dialog-details" header="Details" modal="true" width="95%">
<ui:include src="student_details.xhtml">
<ui:param name="id" value="#{student.id}"/>
</ui:include>
</p:dialog>
Finally, the details page was changed to be something like this:
<ui:composition
xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui" xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<f:metadata>
<f:viewParam name="id" value="#{studentBean.id}" />
</f:metadata>
<h1 class="title ui-widget-header ui-corner-all">Details of #{studentBean.bean.name} / #{studentBean.bean.number}</h1>
</ui:composition>
When I click the button, the dialog really shows and the content is the details page. I see the following content in the dialog:
Details of /
No errors at all, but the data that should be shown, isn't. A breakpoint was set in StudentBean.setId() (this method loads a property named bean with the Student instance corresponding to the passed id) but it is never hit.
After some time thinking about it, I came to understand why it does not work. The parameter passed to the details page is student.id, but student is the name used as the var in the <p:datatable/> that show all the students, so student is not valid in <p:dialog/> which is outside the <p:datatable/>.
So, what I need is a way to show the dialog using the id of the corresponding student in a given row. Ideally, I would like an ajax call here, so the details would loaded only when neded.
Any ideas?
The button should be an ajax button which sets the currently iterated entity in the bean, and then updates the dialog's content, and finally shows it. The dialog should just reference that entity in the bean and update the list and table on save. It's very important that dialog is placed outside the main form and that it has its own form.
Here's a kickoff example:
<h:form id="master">
<p:dataTable value="#{bean.entities}" var="entity">
<p:column>#{entity.property1}</p:column>
<p:column>#{entity.property2}</p:column>
<p:column>#{entity.property3}</p:column>
...
<p:column>
<p:commandButton value="View" action="#{bean.setEntity(entity)}"
update=":detail" oncomplete="PF('detail').show()" />
</p:column>
</p:dataTable>
</h:form>
<p:dialog id="detail" widgetVar="detail">
<h:form>
<p:inputText value="#{bean.entity.property1}" />
<p:inputText value="#{bean.entity.property2}" />
<p:inputText value="#{bean.entity.property3}" />
...
<p:button value="Close" onclick="PF('detail').hide(); return false" />
<p:commandButton value="Save" action="#{bean.save}"
update=":master" oncomplete="if(!args.validationFailed) PF('detail').hide()" />
</h:form>
</p:dialog>
With this inside a #ViewScoped bean:
private List<Entity> entities; // +getter
private Entity entity; // +getter+setter
#EJB
private EntityService entityService;
#PostConstruct
public void load() {
entities = entityService.list();
entity = null;
}
public void save() {
entityService.save(entity);
load();
}
See also:
Creating master-detail pages for entities, how to link them and which bean scope to choose
Creating master-detail table and dialog, how to reuse same dialog for create and edit
Keep p:dialog open when a validation error occurs after submit
Difference between rendered and visible attributes of <p:dialog>
How to display dialog only on complete of a successful form submit
This odd behavior only happen in Firefox (specifically Firefox 8). So I have a dataTable that I can do multiple selection. A submit button, that will display a list of selected items to a dataList and to a dialog. If the user did not select anything, then a error msg come up asking the user to select something. The dialog will not appear if the user select nothing. The below code does all that. However FireFox behaves oddly if you do these follow:
Click to select an item on the dataTable
Then refresh (F5 or Ctl + R) the page (you can see the selection got clear off)
Then click submit, it show whatever I just selected.
This is unexpecting, since the refresh should clear out whatever you just select due to nature of #ViewScoped bean. This behavior only happen in Firefox. IE 8 behave correctly for me. Is this a bug, or am I doing something wrong here?
Mojarra 2.1 + PrimeFaces3.0 Final + Tomcat 7
UPDATE: I did some debugging, when I refresh page, the value of the array selectedFoods become null, but for some odd reason, when it get to public void checkSelection(), it hold the value of the previous selection. So odd.
Here is my code.
<p:growl id="messages" showDetail="true" />
<p:messages id="msgs"/>
<h:form id="form">
<p:dataTable value="#{viewBean.foodList}" var="item"
selection="#{viewBean.selectedFoods}"
selectionMode="multiple"
rowKey="#{item}">
<p:column>
#{item}
</p:column>
<f:facet name="footer">
<p:commandButton value="Submit" update=":form:display :dataList"
action="#{viewBean.checkSelection}"/>
</f:facet>
</p:dataTable>
<p:dataList id="display" value="#{viewBean.selectedFoods}" var="item"
itemType="disc">
#{item}
</p:dataList>
</h:form>
<p:dialog id="dialog1" widgetVar="dialog1" dynamic="true" width="200">
<p:dataList id="dataList" value="#{viewBean.selectedFoods}" var="item"
itemType="disc">
#{item}
</p:dataList>
</p:dialog>
Here is my managed bean
#ManagedBean
#ViewScoped
public class ViewBean implements Serializable {
private List<String> foodList;
private String[] selectedFoods;
#PostConstruct
public void init() {
foodList = new ArrayList<String>();
foodList.add("Pizza");
foodList.add("Pasta");
foodList.add("Hamburger");
}
public void checkSelection(){
RequestContext requestContext = RequestContext.getCurrentInstance();
if(selectedFoods.length > 0){
requestContext.execute("dialog1.show()");
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Error", "Please select"));
requestContext.addPartialUpdateTarget("messages");
}
}
//setter, getter
}
Your code is fine. What you're seeing is because of something that is supposed to be a feature of Firefox (I was able to reproduce this on FF4). The selection model for p:dataTable is implemented with a hidden form field. When reloading a page, Firefox tries to save and restore form field values that have changed so that you don't lose what you entered. You can observe this by adding a <h:inputText/> to your view, typing something in the input, and reloading.
I'm not sure that the Firefox team meant for this to apply to hidden form fields, but I figure there's a decent chance that they did. I plan to file a bug report with Primefaces to either initialize the hidden input or to read the input on load to make the p:dataTable selection match. Either solution should result in the rendered selection and the hidden selection model to be in sync.