JSF submitButton that renders on datatable - ajax

This is my JSF(2.2) page :
<h:form>
<p>
Hiker-name
</p>
<p>
<h:selectOneMenu id="smenu">
<f:ajax render="hikerActivities"/>
<c:forEach items="#{hikerPresenter.hikers}" var="hiker">
<f:selectItem itemValue="#{hiker.hikerId}" itemLabel="#{hiker.hikerName}"/>
</c:forEach>
</h:selectOneMenu>
<h:commandButton id="submitHiker" value="Submit" action="#{hikerPresenter.getHikerActivities(hiker.hikerId)}">
<f:ajax execute="smenu" render="hikerActivities"/>
</h:commandButton>
</p>
<p>
<h:dataTable id="hikerActivities" var="hikerActivity" border="1">
<h:column>
<f:facet name="header" >Trip-date</f:facet>
#{hikerActivity.tripDate}
</h:column>
<h:column>
<f:facet name="header">Trip-fare</f:facet>
#{hikerActivity.tripFare}
</h:column>
<h:column>
<f:facet name="header">Trip-duration</f:facet>
#{hikerActivity.tripDuration}
</h:column>
</h:dataTable>
</p>
I want that with a click on the command button, my MBean's method get called with the hikerId from the selected item and gets render on the datatable.
this is my MBean :
#ManagedBean
#RequestScoped
public class HikerPresenter {
#EJB
private HikerControllerLocal hikerController;
public HikerPresenter() {
}
public List<HikerAccessDTO> getHikers(){
return hikerController.getHikers();
}
public List<HikerActivityDTO> getHikerActivities(long hikerId){
System.out.println("Get Hiker Activities Called");
List<HikerActivityDTO> l = new ArrayList();
l.add(new HikerActivityDTO(new Date(1417150800000L), "Montréal", "Valleyfield", "Amine", 22, 45));
l.add(new HikerActivityDTO(new Date(1417160800000L), "Montréal", "Québec", "Farida", 33, 44));
l.add(new HikerActivityDTO(new Date(1417170800000L), "Montréal", "Alloha", "dsdsd", 12, 2332));
return l;
}
}
I suppose that I call the MBean method getHikerActivities on the wrong place because it doesn't even System.out.
What am-I doing wrong?

1:
use f:selectItems instead of f:selectItem
2:
your table missed the value attribute like value="hikerPresenter.hikers"
3:
You must set the value attribute of h:selectOneMenu to set hikerId into the bean, so its not necessary to send it as parameter in the method getHikerActivities

Related

Change value of checkbox using ajax in JSF

I try to solve the following problem: i have a group of h:selectBooleanCheckbox that generates using ui:repeat:
<h:form>
<ui:repeat value="#{uiCheckboxList.list}" var="boxElement" varStatus="i">
<h:selectBooleanCheckbox id="a">
<f:attribute name="value" value="#{boxElement.enabled}"/>
</h:selectBooleanCheckbox>
<h:outputLabel value="#{boxElement.val}" for="a"/>
</ui:repeat>
</h:form>
Values and label's text stored in array list and controls by servlet:
#ManagedBean(name="uiCheckboxList")
#ApplicationScoped
public class CheckBoxListBean implements Serializable {
private ArrayList<BoxTuple> list;
// BoxTyple is class with 2 fields - val (double) and enabled (boolean)
public CheckBoxListBean() {
list = new ArrayList<>();
for(double i = -2.0; i <= 2.0; i += 0.5) {
list.add(new BoxTuple(i, false));
}
// Set first element to true
list.get(0).setEnabled(true);
}
public ArrayList<BoxTuple> getList() {
return list;
}
public void setList(ArrayList<BoxTuple> list) {
this.list = list;
}
And my problem is this: when you click on one of the h:selectBooleanCheckbox server asynchronously sent request with information about the changed box, and then change the values of the another boxes without reloading page. In other words, I need to get the behavior of radio boxes. Maybe it sounds silly, but I need to solve this problem. How can i implement this?
You can do something like this:
<h:form id="form">
<ui:repeat value="#{uiCheckboxList.list}" var="boxElement"
varStatus="i">
<h:selectBooleanCheckbox id="a">
<f:attribute name="value" value="#{boxElement.enabled}" />
<f:ajax render="form"
listener="#{uiCheckboxList.listen(boxElement)}" />
</h:selectBooleanCheckbox>
<h:outputLabel value="#{boxElement.val}" for="a" />
</ui:repeat>
</h:form>
(get rid of the varStatus if you don't use it)
public void listen(BoxTuple tuple) {
if (tuple.enabled)
for (BoxTuple t : list)
if (!t.equals(tuple))
t.setEnabled(false);
}

AJAX not rendering in JSF

Sorry for my english.
Method delete from TestMB:
public String delete(Post post) {
getDao().delete(post);
return "success";
}
test.xhtml :
<h:form id="form1">
<ui:repeat value="#{TestMB.entityList}" var="entityList">
<p>
#{entityList.name}
<h:commandLink action="#{TestMB.delete(entityList)}">
del
<f:ajax render=":form1"/>
</h:commandLink>
</p>
</ui:repeat>
</h:form>
Page does not refresh when I clicked the link "del". If I click again, the page will refresh. Why?
if I use new method delete from TestMB:
private String txt1="test";
public String delete() {
try{
Thread.sleep(Long.valueOf("10000"));
}catch(Exception ex){}
txt1="";
return "";
}
And new test.xhtml:
<h:form id="form1">
#{testMB.txt1}
<h:commandLink action="#{testMB.delete}">
del
<f:ajax render=":form1"/>
</h:commandLink>
</h:form>
I click the link "del" and the page refresh in 10 seconds.
Why not work in the first case?
I found the problem.
public List<Entity> getEntityList() {
//if(entityList == null){
entityList=getDao().findAll(getPageRequest());
//}
return entityList;
}

How to validate p:pickList to require at least one selection

I have used column picklist to customize columns of table on page and I want to show dialog message (Atleast one column should be enabled) if user disables all the columns from picklist. That means user should keep atleast one column in enable box.
<p:dialog id="pickListDialog" header="Customize View"
widgetVar="dlg">
<h:panelGrid>
<p:pickList id="columnPickList"
value="#{Class_Name.columns}" var="col"
itemLabel="#{Class_Name.columnPickList.columnsDisplayMap.get(col)}"
itemValue="#{col}">
<f:facet name="sourceCaption">Disabled</f:facet>
<f:facet name="targetCaption">Enabled</f:facet>
</p:pickList>
<p:commandButton value="Submit"
actionListener="#{Class_Name.columnPickList.saveColumns}" onclick="return disableClick();"
ajax="false" />
</h:panelGrid>
</p:dialog>
Javascript method -
function disableClick(){
if (document.getElementById("form:columnPickList_target").value == ""){
alert("Please Select Atleast One Field");
return false;
}
}
Here I have used Javascript for this. But I want to do this by JSF .
can anyone please tell me ?
Case 1 : Using required attribute
<p:pickList id="columnPickList" required="true" requiredMessage="Atleast one column should be enabled"
value="#{Class_Name.columns}" var="col"
itemLabel="#{Class_Name.columnPickList.columnsDisplayMap.get(col)}"
itemValue="#{col}">
<f:facet name="sourceCaption">Disabled</f:facet>
<f:facet name="targetCaption">Enabled</f:facet>
</p:pickList>
Case 2 : Opening dialog from backing bean
public void saveColumns()
{
validateColumns();
//doSomthing
}
public void validateColumns() {
//check if picklist target is empty
if(columns.getTarget().size()==0)
{
//open dialog
message="Atleast one column should be enabled";
RequestContext.getCurrentInstance().execute("validationDialog.show()");
}
}
private String message; //getter and setter
dialog :
<p:dialog id="valid" widgetVar="validationDialog">
<p:outputLabel value="#{yourbean.message}" />
</dialog>

Problems with ajax in jsf updating an output text field

I'm new to JSF and in class we should just set up a little "Pizza-Service" with logins etc. On the Page where i want to prepare my Order as a user I've a data table (primeface data table) with 4 columns. The last one is for the number of pizza of the type in the current cell.
What I want: If I am typing in a Number i want to set up a current Order (works fine so far with ajax) in the same moment i just want to show the user the current price. This is the little thing that is not working.
When I am using the tag there is just nothing happening and if I am taking the tag I'm getting this mistake:
<f:ajax> contains an unknown id 'ausgabe' - cannot locate it in the context of the component menge
What I thought was take the ajax tag set up a function (take the current order) and render an output text where the calculated price is shown directly. I called those function in german so bestellungAufnehmen = takeOrder and preisBerechnen = calculatePrice.
Thanks if someone could help me!
Here is the xhtml:
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<p:dataTable id="table" var="pizza" value="#{model.getPizzen()}">
<p:column headerText="Nr">
<h:outputText value="#{pizza.nr}"/>
</p:column>
<p:column headerText="Artikel">
<h:outputText value="#{pizza.name}"/>
</p:column>
<p:column headerText="Preis">
<h:outputText value="#{pizza.preis}"/>
</p:column>
<p:column headerText ="Menge">
<h:inputText id="menge" value="#{bestellung.anzahl}">
<f:ajax event="keyup" render="ausgabe" listener="#{bestellung.bestellungAufnehmen(pizza)}"/>
</h:inputText>
</p:column>
</p:dataTable>
<h:outputLabel value="Zu Zahlen: "/>
<h:outputText id="ausgabe" value="#{bestellung.preisBerechnen()} €"/>
</h:form>
</h:body>
and here is the the Bean with those functions.
#Named
#SessionScoped
public class Bestellung implements Serializable {
private static int bstzaehler=0;
private int bstnr;
private Map<String,Bestellposten> posten;
private int anzahl;
public Bestellung(){
this.bstnr=++bstzaehler;
this.posten = new HashMap<>();
}
/**
* #return the bstnr
*/
public int getBstnr() {
return bstnr;
}
/**
* #param bstnr the bstnr to set
*/
public void setBstnr(int bstnr) {
this.bstnr = bstnr;
}
public void bestellungAufnehmen(Pizza pizza){
if(this.posten.containsKey(pizza.getName()) == false){
Bestellposten b = new Bestellposten(this.getAnzahl(), pizza);
this.posten.put(pizza.getName(),b);
} else {
if(this.getAnzahl() > 0 ){
Bestellposten tmp = this.posten.get(pizza.getName());
tmp.setMenge(this.getAnzahl());
} else {
this.posten.remove(pizza.getName());
}
}
System.out.println("groesse: "+posten.size());
System.out.println("akt preis: "+this.preisBerechnen());
}
/**
* #return the anzahl
*/
public int getAnzahl() {
return anzahl;
}
/**
* #param anzahl the anzahl to set
*/
public void setAnzahl(int anzahl) {
this.anzahl = anzahl;
}
public double preisBerechnen(){
double sum = 0.0;
for(String key : this.posten.keySet()){
Pizza tmp = this.posten.get(key).getPizza();
sum += tmp.getPreis() * this.posten.get(key).getMenge();
}
return sum;
}
}
Try giving the full qualified id for the component:
<h:form id="frmPizza">
<p:dataTable id="table" var="pizza" value="#{model.getPizzen()}">
<p:column headerText="Nr">
<h:outputText value="#{pizza.nr}"/>
</p:column>
<p:column headerText="Artikel">
<h:outputText value="#{pizza.name}"/>
</p:column>
<p:column headerText="Preis">
<h:outputText value="#{pizza.preis}"/>
</p:column>
<p:column headerText ="Menge">
<h:inputText id="menge" value="#{bestellung.anzahl}">
<f:ajax event="keyup" render=":frmPizza:ausgabe" listener="#{bestellung.bestellungAufnehmen(pizza)}"/>
</h:inputText>
</p:column>
</p:dataTable>
<h:outputLabel value="Zu Zahlen: "/>
<h:outputText id="ausgabe" value="#{bestellung.preisBerechnen()} €"/>
</h:form>
I think, you should use update attribute to update that outputText, like update=":FormId:ausgabe"
<f:ajax event="keyup"
render=":frmPizza:ausgabe"
listener="#{bestellung.bestellungAufnehmen(pizza)}"
update=":frmPizza:ausgabe" />
The solution of luiggi worked but i couldnt answer directly because of my "low-level" here.
Iam not on my computer right now but isnt "update" an attribute of p:ajax and not of f:ajax and is the same as render? but i will try it aswell later on.
thx!

Issue faced with Trinidad Table, Partial Trigger, and Read Only

I have a trinidad table with one column contains drop downs (select one choice) for each row and another column contains an input text for each row.
When a particular option is selected, the input becomes editable (else it remains read only).
The read only behaviour and the partial event are working perfectly as expected. The problem is whenever the input text is supposed to move from editable to read only, I still see the value previously entered when the input text was editable.
From here if I select another option (for which the input text would also be read only) the value goes away.
The JSP Code is as follows:
<tr:table emptyText="No Data" var="vo" autoSubmit="true" partialTriggers="accountType" value="#{testingBean.voList}" binding="#{testingBean.table}" width="50%">
<tr:column>
<f:facet name="header">
<tr:outputText value="Sl No" />
</f:facet>
<tr:outputText value="#{vo.slNo}" />
</tr:column>
<tr:column>
<f:facet name="header">
<tr:outputText value="Account Type" />
</f:facet>
<tr:selectOneChoice unselectedLabel="Select" id="accountType" value="#{vo.accountType}"
autoSubmit="true" immediate="true" valuePassThru="true"
valueChangeListener="#{testingAction.optionsChanged}">
<f:selectItems value="#{testingBean.options}" />
</tr:selectOneChoice>
</tr:column>
<tr:column>
<f:facet name="header">
<tr:outputText value="Other" />
</f:facet>
<tr:inputText value="#{vo.otherType}"
partialTriggers="accountType"
readOnly="#{vo.readOnlyFlag}"></tr:inputText>
</tr:column>
</tr:table>
The code for the valueChangeListener is as follows:
public void optionsChanged(ValueChangeEvent vce) {
try {
System.out.println("Inside Method");
testingBean = (TestingBean) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("testingBean");
ArrayList<TableRowVO> list = testingBean.getVoList();
UIXTable table = testingBean.getTable();
TableRowVO vo = list.get(table.getRowIndex());
vo.setReadOnlyFlag(true);
vo.setAccountType(vce.getNewValue().toString());
vo.setOtherType("");
if (vce.getNewValue().equals("3")) {
System.out.println("Setting false");
vo.setReadOnlyFlag(false);
}
list.set(table.getRowIndex(), vo);
table.setValue(list);
testingBean.setVoList(list);
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("testingBean", testingBean);
} catch (Exception e) {
e.printStackTrace();
}
}
Is this behaviour expected? Or is there a workaround?
Interestingly, the "View Page Source" option in Firefox does not contain the text, even though I can see it on the page. I had to use FireBug to analyze the element which revealed the following:
<div class="af_inputText_content"
id="j_id_jsp_545172797_17:0:j_id_jsp_545172797_27">
tttt
</div>
Version used:
Trinidad 2.x
JSF 2.x
Tomcat 7.0
Ok, so I got it to work a while back but forgot to post the answer....
I used FacesContext to find the CoreComponent for the input text and then reset the components value.
Basically:
Find the CoreTable object
Find the CoreColumn object
Find the CoreInputText object
Reset the value for CoreInputText
The Modified JSP Code is as follows:
<tr:table emptyText="No Data" var="vo" autoSubmit="true" partialTriggers="accountType" id="voTable" value="#{testingBean.voList}" binding="#{testingBean.table}" width="50%">
<tr:column id="slNoCol">
<f:facet name="header">
<tr:outputText id="slNoHdr" value="Sl No" />
</f:facet>
<tr:outputText id="slNo" value="#{vo.slNo}" />
</tr:column>
<tr:column id="accountTypeCol">
<f:facet name="header">
<tr:outputText id="accountTypeHdr" value="Account Type" />
</f:facet>
<tr:selectOneChoice unselectedLabel="Select" id="accountType" value="#{vo.accountType}" autoSubmit="true" immediate="true" valuePassThru="true" valueChangeListener="#{testingAction.optionsChanged}">
<f:selectItems value="#{testingBean.options}" />
</tr:selectOneChoice>
</tr:column>
<tr:column id="otherTypeCol">
<f:facet name="header">
<tr:outputText id="otherTypeHdr" value="Other" />
</f:facet>
<tr:inputText value="#{vo.otherType}" columns="15" partialTriggers="accountType" id="otherType" readOnly="#{vo.readOnlyFlag}" immediate="true">
</tr:inputText>
</tr:column>
</tr:table>
The code for the modified valueChangeListener is as follows:
public void optionsChanged(ValueChangeEvent vce) {
try {
testingBean = (TestingBean) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("testingBean");
ArrayList<TableRowVO> list = testingBean.getVoList();
CoreTable table = (CoreTable) FacesContext.getCurrentInstance()
.getViewRoot().findComponent("voTable");
CoreColumn column = (CoreColumn) table
.findComponent("otherTypeCol");
CoreInputText text = (CoreInputText) column
.findComponent("otherType");
text.setValue("");//This is the trick....
TableRowVO vo = list.get(table.getRowIndex());
vo.setReadOnlyFlag(true);
vo.setAccountType(vce.getNewValue().toString());
vo.setOtherType("");
if (vce.getNewValue().equals("3")) {
vo.setReadOnlyFlag(false);
}
list.set(table.getRowIndex(), vo);
table.setValue(list);
testingBean.setVoList(list);
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("testingBean", testingBean);
} catch (Exception e) {
e.printStackTrace();
}
}

Resources