Primefaces DialogFramework close on init - jsf

I have the same requirement as mentioned in "
primefaces close dialog on init don't work" but the only answer is not a working solution, becaue in Dialog Framework i don't have a widgetVar.
My #PostConstruct method looks similar:
#PostConstruct
private void init() {
Tree tree = initTree();
if (tree.getChildCount() == 1) {
// #todo close dialog if tree has only 1 child
// this does not close the dialog
RequestContext.getCurrentInstance().closeDialog(true);
// this does not work, because there is no widgetVar
//RequestContext.getCurrentInstance().execute("yourDialogWidgetVar.close()");
}
}
So, how can I close a DialogFramework xhtml page from its #PostConstruct method ?
I'm using Primefaces 6.0 on Wildfly 10.0.0.Final

Related

How to programatically open a dialog box in primefaces without user click?

I am working on an exam management session using Java EE 7 and Primefaces. Tests are timed and once the time is over, I want to display a dialog box automatically(i.e. without user clicking any button). I successfully used Primefaces Dialog framework on the click of a button, but can't do it automatically.
For timing the test I am using TimerService, which calls a stateless EJB's method on timeout. I have a session scoped CDI bean which creates the timer.
This is the post construct method of the CDI bean.
public void init() {
studentAnswers = new ArrayList<StudentAnswer>();
examSections=ePaper.getSections();
examTimerBean.createExamPaperDuration(10,RequestContext.getCurrentInstance());
}
The stateless EJB is as follows -
#Stateless
public class ExamTimerBean {
#Resource TimerService timerService;
RequestContext reqCtx;
public void createExamPaperDuration(int duration,RequestContext reqCtx){
this.reqCtx=reqCtx;
timerService.createTimer(duration*1000, null);
}
#Timeout
public void examTimeExpired(){// throws IOException{
try{
reqCtx.openDialog("thanks");
}
catch(EJBException e){
System.out.println(e.getMessage());
}
}
}
I am passing the request context to the EJB, but the dialogBox doesn't open. Kindly help.

Submitting programmatically created jsf form

I have created jsf form at backing bean. I have created form, it is being shown on screen with values successfully. When I click sumbit button, backing bean method is invoked with ActionEvent but updated input values are not submitted to backend. Backign bean entity object values are not updated.
Is there any wrong? Thanks so much for your helps,
Br.
Ramazan
HtmlForm form = new HtmlForm();
form.setId(appletWrapper.getName()+"_FORM");
PanelGrid panelGrid = (PanelGrid)createComponent(PanelGrid.COMPONENT_TYPE);
form.getChildren().add(panelGrid);
panelGrid.setColumns(4);
panelGrid.setId(appletWrapper.getName()+"_FORM_PANEL");
for (FieldWrapper fieldWrapper : appletWrapper.getFields()) {
panelGrid.getChildren().add(new UIFieldLabel(fieldWrapper).component(entities));
panelGrid.getChildren().add(newFieldComponent(fieldWrapper, entities));
}
HtmlPanelGroup panelGroup = new HtmlPanelGroup();
panelGroup.setId(appletWrapper.getName()+"_PANEL_GROUP");
panelGrid.getFacets().put("footer", panelGroup);
CommandButton commandButton = new CommandButton();
panelGroup.getChildren().add(commandButton);
commandButton.setId(appletWrapper.getName()+"_UPDATE");
commandButton.setAjax(true);
commandButton.setValue("update");
commandButton.setProcess("#this");
commandButton.setType("submit");
MethodExpression updateEntityME = createMethodExpression("#{mainBean.entityUpdateListener}", null, new Class[] {ActionEvent.class });
commandButton.addActionListener(new MethodExpressionActionListener(updateEntityME));
return form;
Edited: I gave all components a fixed id.
One of my coponents genarated like that;
InputText inputText = (InputText)createComponent(InputText.COMPONENT_TYPE);
inputText.setId(fieldAlphanumericWrapper.getName());
inputText.setValueExpression("value", createValueExpression("#{mainBean.selection."+fieldAlphanumericWrapper.getProperty()+"}", Object.class));
return inputText;
My backing bean target method;
public void entityUpdateListener(ActionEvent actionEvent) {
TAccount tAccount = (TAccount)getSelection();
System.out.println("tAccount.gettWebsite():"+tAccount.gettWebsite());
}
The main problem is that actually; When I press commandButton mainBean.setSelection is not invoked, so backing bean object is not updated. I cant take updated object instance through actionEvent instance.
I found solution, cause of problem was this line;
commandButton.setProcess("#this");
I have changed to this and problem solved.
commandButton.setProcess("#form");
Br.
Ramazan

Calling Primefaces dialog box from Managed Bean function

Hi I have a managed bean with some functions , based on some condition in that function I will like to call a dialog box
Managed bean function goes as
public String editStudent(){
setReadOnly(false);
setButton(true, true, true, false, true, true,true);
LockItem lItem;
if(selectStudent !=null){
lItem = (LockItem) services.getbyId("LockItem", condition);
if (lItem == null){
System.out.println("Student Avalibale for process :::");
studentRedirect();
return "studentEdit.jsf?faces-redirect=true";
} else {
//To show dialog from here
System.out.println("Student Not Avalibale : Locked By " + lItem.getLockedBy());
}
} else {
FacesMessage msg;
msg = new FacesMessage("Please select the record.");
FacesContext.getCurrentInstance().addMessage(null, msg);
return show("menu");
}
}
Is there any method using which we can call the dialog box from such managed function
You can, by using the RequestContext (or PrimeFaces if you are using the version 6.2 or higher) class.
Suppose you have the following:
<p:dialog id="myDialogID" widgetVar="myDialogVar">
....
</p:dialog>
So the way you do in the facelet itself, i.e. onclick=myDialogVar.show();, the same can be done in your managed bean like so:
For PrimeFaces <= 3.x
RequestContext context = RequestContext.getCurrentInstance();
context.execute("myDialogVar.show();");
For PrimeFaces >= 4.x to PrimeFaces < 6.2 (as per #dognose and #Sujan)
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('myDialogVar').show();");
For PrimeFaces >= 6.2
PrimeFaces current = PrimeFaces.current();
current.executeScript("PF('myDialogVar').show();");
This is for using targeted dialogs. If you just need to show a message without giving preference to any custom dialog, then you can do it this way:
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message Title", "Message body");
// For PrimeFaces < 6.2
RequestContext.getCurrentInstance().showMessageInDialog(message);
// For PrimeFaces >= 6.2
PrimeFaces.dialog().showMessageDynamic(message);
You can pass in arguments and set callbacks as well. Refer to the showcase examples in the link.
See also:
Primefaces Dialog framework
If you are on primeface 4.0 Or Above:
RequestContext.getCurrentInstance().execute("PF('yourdialogid').show()");
Vrushank's solution is correct.
There is also another way: in your dialog, bind rendered attribute to a boolean value of your bean, and set the visible attribute to true, like this:
<p:confirmDialog
widgetVar="myDialog"
visible="true"
rendered="#{myBean.showMyDialog}">
In action listener in your bean, you just call setShowMyDialog(true), and a dialog will show (assuming your dialog is being updated by this action). This approach is useful if for some reason you don't want your dialog's HTML to be rendered when it is not visible to the user. This way, in your bean you have access to information, whether your dialog is visible.
Another benefit of this solution is, that your dialog is not hidden on ajax update (of dialog or its parent).

JSF - p:ajax listener asking for parameters netBeans/primefaces

Versions:
NetBeans: 7.2.1
PrimeFaces: 3.5.3
GlassFish: 3.1.2
JDK 1.6
I've been trying to find related issues and have found topics that are close, but not quite what I'm looking for. I'm trying to do something similar to the p:schedule demo from PrimeFaces ShowCase where I want a dialog to appear showing the details of the event clicked.
I think the issue is coming from calling the listener method from the backing bean. When I go to type in the listener method in the p:ajax tag, NetBeans forces me to pass in a parameter like:
listener="#{cmodel.onEventSelect(e)}"
which I don't think is necessary as I don't have a value to pass in anyways.
I'm thinking either:
Something is up with NetBeans that doesn't recognize the method as a listener. (Since i keep seeing multiple examples of people calling the method without needing to pass a parameter.)
or
I'm not registering the method as a listener properly in the Model.
Also, I have directly copied and pasted the demo from the ShowCase into a project and it didn't work which is making me lean more towards an issue with NetBeans. (that is, the dialog appears but with no information on the event that was selected)
So to summarize; events are showing up as they should on the schedule itself, I just cant get the dialog to show the event details of the event that was selected.
Any help would be greatly appreciated!
View Layer:
<h:form>
<p:schedule id="nelsonsSchedule" value="#{cmodel.scheduleModel}" showHeader="true"
leftHeaderTemplate="none" rightHeaderTemplate="prev, next today"
draggable="false" timeZone="UTC" styleClass="schedule">
<p:ajax event="eventSelect" listener="#{cmodel.onEventSelect}"
update="eventDialog eventDetails" oncomplete="eventDialog.show()"/>
</p:schedule>
<p:dialog id="eventDialog" widgetVar="eventDialog" header="EventDetails">
<p:panel id="eventDetails">
<h:outputLabel value="#{cmodel.selectedEvent.title}" />
</p:panel>
</p:dialog>
</h:form>
Backing Bean:
#ManagedBean(name = "cmodel")
#SessionScoped
public class CalendarModel implements Serializable {
private ScheduleModel scheduleModel;
private List<ScheduleEvent> allScheduledGames;
private DefaultScheduleEvent gameEvent;
public ScheduleEvent selectedEvent;
List<Game> allGames;
#PersistenceContext
private EntityManager em;
public CalendarModel() {
}
#PostConstruct
public void init() {
allScheduledGames = new ArrayList<ScheduleEvent>();
allGames = new ArrayList<Game>();
allGames = em.createNamedQuery("Game.findAll").getResultList();
/*create list of games to put into the ScheduleModel*/
for (int i = 0; i < allGames.size(); i++) {
gameEvent = new DefaultScheduleEvent(allGames.get(i).getOpponent() +
"\n\n\n" + allGames.get(i).getTimeOfGame(),
allGames.get(i).getDateOfGame(),
allGames.get(i).getDateOfGame());
if(allGames.get(i).getHomeAway().equals("away")){
gameEvent.setStyleClass("away");
} else{
gameEvent.setStyleClass("home");
}
gameEvent.setData(allGames.get(i));
allScheduledGames.add(gameEvent);
}/*end for*/
scheduleModel = new DefaultScheduleModel(allScheduledGames);
}/*end init()*/
public void onEventSelect (SelectEvent e) {
selectedEvent = new DefaultScheduleEvent();
selectedEvent = (ScheduleEvent) e.getObject();
}
In case anyone runs into the same issue - It was NetBeans. I upgraded to 7.3 and don't have the problem anymore. Although another has come up where itellisense doesn't recognize a hashmap from the backing bean, but that's for another question.

JSF preload list for datatable in page [duplicate]

This question already has an answer here:
How and when should I load the model from database for JSF dataTable
(1 answer)
Closed 7 years ago.
I'm using EJB and JSF. I made a jsp simple page with a button "get list". When it's clicked, a managed bean method is called that sets the list, which is then displayed in the jsp with the dataTable tag.
The question is, how can I pre load this list/dataTable on page load without having to click the button?
This is the method that's called through the button action on the jsp:
public String retrieveList() {
items = facade.getAllItem();
return "";
}
this is the part of the jsp:
<h:dataTable value="#{mybean.items}" var="sup"
binding="#{mybean.dataTable}"
rowClasses="oddRow, evenRow"
styleClass="tableStyle"
headerClass="tableHeader"
columnClasses="column1, column2, column1, column1, column1, column1">
You can add a method init with #postConstruct
#PostConstruct
public void init(){
items = facade.getAllItem();
}
This will return the items only on bean creation ,
Annotate the method with #PostConstruct and get rid of return value.
#PostConstruct
public void retrieveList() {
items = facade.getAllItem();
}
This way the method will be executed immediately after construction of the bean and injection of all #EJB dependencies. In the JSF page you just have to bind to #{bean.items} the usual way.

Resources