I have a p:selectOneMenu in my application, and when the selection takes place I need to call multiple back-end methods from different managed beans in order to perform different actions.
XHTML code:
<p:selectOneMenu id="selectMenu" value="#{userBean.selectedSite}"
converter="siteConverter" style="width:150px">
<p:ajax event="change" listener="#{bean2.changeSite}"
render="#form :comp1 :comp2 :comp3 :comp4" />
<f:selectItems value="#{userBean.sites}" var="site"
itemValue="#{site}" itemLabel="#{site.description}" />
<p:ajax event="change" listener="#{bean1.reset}"
update="#form :comp1 :comp2 :comp3 :comp4" />
</p:selectOneMenu>
Managed bean 1:
#ManagedBean(name="bean1")
#ViewScoped
public class Bean1 implements Serializable {
// ...
public void reset() {
loadEvents();
resetEvent();
}
}
Managed bean 2:
#ManagedBean(name="bean2")
#SessionScoped
public class Bean2 implements Serializable {
// ...
public void changeSite() {
FacesContext context = FacesContext.getCurrentInstance();
Bean1 bean = (Bean1) context.getApplication().evaluateExpressionGet(context, "#{bean1}", Bean1.class);
reload();
bean.loadEvents();
}
}
If, instead of using two different p:ajax components, I use a single p:ajax that calls a single method from Bean1, the page components listed under "update" are not correctly updated.
XHTML:
<p:ajax event="change" listener="#{bean1.singleMethod}"
update="#form :comp1 :comp2 :comp3 :comp4" />
Managed bean 1:
#ManagedBean(name="bean1")
#ViewScoped
public class Bean1 implements Serializable {
// ...
public void () singleMethod() {
FacesContext context = FacesContext.getCurrentInstance();
Bean2 bean = (Bean2) context.getApplication().evaluateExpressionGet(context, "#{bean2}", Bean2.class);
bean2.changeSite();
reset();
}
}
Changing the selected values updates the server side objects, but the page is not updated: if I press F5, the page shows the actual situation.
Moving the single global method to the session scoped bean (Bean2) does the job.
Related
I have the following menu items in index.xhtml
<p:menuitem ajax="false" value="A" action="#{bean.start('A')}" />
<p:menuitem ajax="false" value="B" action="#{bean.start('B')}" />
The following code on my backing bean doesn't work when the bean is ViewScoped (I don't want to make it SessionScoped):
#Named
#ViewScoped
public class Bean implements Serializable {
private LetterEnum letter;
public String findBSEmpty(String str) {
if (saison.equals("A")) {
this.letter = LetterEnum.A;
return "a.xhtml";
} else {
this.letter = LetterEnum.B;
return "b.xhtml";
}
}
public void doSomthing(){
//Method called from other a.xhtml and b.xhtml
//Processing data depending on the value of "letter"
}
I know that view scoped beans are recycled after every view change and I have must start from index.xhtml and depending on the choice of the user, the application will display a.xhtml or b.xhtml to continue processing other data.
Am I missing somthing?
What are the best practices about this kind of navigation?
BTW, I am using JSF 2.2 with Payara 4
I am very new to ajax and trying to copy the value of one box to another. Here is my code:
<h:form>
<h:inputText value="#{ajaxBean.name}">
<f:ajax render="otherbox" execute="#this" event="keyup"></f:ajax>
</h:inputText>
<h:inputText id="otherbox" value="#{ajaxBean.name}"></h:inputText>
</h:form>
And the bean
#Named(value = "ajaxBean")
#Dependent
public class AjaxBean {
public AjaxBean() {
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
That code does not work. Can anyone help me?
Thanks
Your question is not about Ajax or JSF. It is a JavaScript question.
You can access and modify items with JavaScript.
Add this JavaScript codes between <h:head></h:head>
<script>
function copyField()
{
document.getElementById("field2").value = document.getElementById("field1").value;
}
</script>
And your page:
<h:form id="myform" prependId="false">
<h:inputText id="field1" value="#{myBean.name}" onkeyup="copyField();" />
<h:inputText id="field2" value="#{myBean.name}"></h:inputText>
</h:form>
Take attention to prependId="false" to avoid mixing ids.
See also:
JSF: Why prependId = false in a form?
I think you are mixing up JSF and CDI. #Dependent says that the bean is in the dependent pseudo-scope (which is anyways the default-scope for CDI-beans), so every time you make a request the bean will be reinstanciated and the bean can not hold any state. Look here for an explanation of the scopes and especially for what the dependent scope is used for.
So first of all you have to use some different scope, #RequestScoped should be enough for your task. And as I do not see any use of CDI here, use #ManagedBean instead of #Named - so the default scope for the bean will be the request scope.
Try this:
#ManagedBean
public class AjaxBean {
...
}
I am trying to make a dynamic menu such that when something is selected in the first selector, the second one is populated from the database based on the selection in the first one. Here is the .xhtml:
<f:view>
<h:form>
<h:selectOneMenu id="seasonSelector" value ="#{selector_bean.season}">
<f:ajax event="valueChange" listener="#{selector_bean.genEvents}"
execute="seasonSelector" render="eventSelector" />
<f:selectItems value ="#{selector_bean.seasons}" var ="s"
itemLabel="#{s.getRange()}"
itemValue="#{s}"></f:selectItems>
</h:selectOneMenu>
<h:selectOneMenu id="eventSelector">
<f:selectItems value ="#{selector_bean.events}" var ="e"
itemLabel="#{e.event_Name}"
itemValue="#{e}"></f:selectItems>
</h:selectOneMenu>
</h:form>
</f:view>
Here is the bean:
#ManagedBean(name = "selector_bean")
#Stateless
public class selector_bean implements Serializable{
#EJB
SeasonFacade sf;
#EJB
EventFacade ef;
#EJB
WrestlerFacade wf;
private Season season;
private Event event;
private List<Event> events;
private Match match;
private Wrestler wrestler;
public List<Season> getSeasons(){
return sf.findAll();
}
public void genEvents(AjaxBehaviorEvent event){
events = (ef.findBySeason(season));
}
// setters and getters after this
When I change the value of the first selectOneMenu, a popup box appears with this message:
httpError: There was an error communicating with the server, status: 404
I am new to both JSF and AJAX so feel free to tear me apart if I am doing it wrong. Thanks for any help!
Your #ManagedBean is behaving as an EJB with the #Stateless annotation. Remove it and instead set the scope of your bean to #ViewScoped:
#ManagedBean(name = "selectorBean")
#ViewScoped
public class SelectorBean implements Serializable{
//your implementation...
}
Also, make sure to follow the JavaBean naming conventions. I've changed the name of your class to start with capital letter.
I want to do multiple actions on different managed beans with the same button, one being scoped session and the other request. In my example I use the same bean for both.
index.xhtml
<h:form>
<p:commandButton image="ui-icon ui-icon-notice" action="#{controller.inc()}" update="result">
<f:actionListener type="controller.Controller" />
</p:commandButton>
</h:form>
<p:panel id="result">
#{controller.count}
</p:panel>
controller.Controller.java
#Named(value = "controller")
#SessionScoped
public class Controller implements ActionListener, Serializable
{
int count = 0;
public Controller(){
System.out.println("new");
}
public void inc(){
count += 1;
}
public int getCount(){
return count;
}
#Override
public void processAction(ActionEvent event) throws AbortProcessingException{
count += 1000;
}
}
When I press the button the count increases by 1, instead of 1001, and creates a new bean. What did I do wrong ?
Thanks.
That's expected behaviour. The <f:actionListener type> creates and gets its own bean instance on every declaration. It does not reuse the same session scoped bean which is managed by JSF.
You need to use binding instead to bind to the already-created session scoped bean instance.
<f:actionListener binding="#{controller}" />
changeThe page has 2 forms. In the first form, the ajax-button initializes an attribute of the viewscoped managed bean. In the second form, the ajax-button uses that attribute to do some stuff. Problem is that the method called by the second form button never gets invoked. Instead, the viewscoped bean is re-initialized and when I hit the same button again, of course the attribute is null resulting in NPE.When I put the 2 buttons within the same form, then everything works as expected.Is this normal: should ajax enabled buttons always reside within the same form?
<h:form id="frmDetail">
<h:commandButton id="btn_changePlant" title="#{msg.ttChangePlant}" immediate="true" image="/resources/img/edit.png">
<f:ajax event="click" render=":fsDetailPlant :headerMsg" listener="{assortiment.detailPlantId}"/>
</h:commandButton>
</h:form>
...some other code ...
<h:form id="frmOffers">
<h:commandButton id="btn_offers" title="#{msg.ttOfferPlant}" immediate="true" value="#{msg.btn_offers}">
<f:ajax event="click" render=":fsDetailPlant :headerMsg" listener="{assortiment.changeOffers}"/>
</h:commandButton>
</h:form>
and the managed bean looks like
#ManagedBean
#ViewScoped
public class Assortiment extends BeanObject implements Serializable {
....
public void detailPlantId(AjaxBehaviorEvent actionEvent) {
clear();
plantdetail = facade.findPlantdetail(plantdetailsIdModel.getRowData());
}
public void changeOffers(AjaxBehaviorEvent actionEvent) {
System.out.println("........ Assortiment.changeOffers(AjaxBehaviorEvent actionEvent)");
if (containerItems.isEmpty()) {
SessieUtils.fillPropertyItems(containerItems, PlantProperty.codeValuesList(ECodeType.logistic, "L02"), facade.getLocale());
}
//
if (offersModel == null) {
offersModel = new ListDataModel<OffersDto>(plantdetail.getOffersList());
}
}
It might just be that the listener attributes need the # prefix,
listener="{assortiment.changeOffers}"
should be
listener="#{assortiment.changeOffers}"