This should be easy for a pro:
I am using JSF/Facelets/Seam and am trying to display radiobuttons. Then, after the user has clicked on one of the buttons, the value should be saved and the user redirected to another page immediately (i.e. with no needed click on a submit button).
The radio button works, but not the forwarding.
Thanks
You can indeed use Richfaces to add an a4j:support component:
<h:selectOneRadio value="#{myBean.myValue}" ...>
...
<a4j:support event="onclick" action="#{myBean.doSomething}"/>
</h:selectOneRadio>
In your Java code:
public String doSomething() {
// Your code goes here...
...
// Now, we move to the new page.
return "some-outcome";
}
However, if you cannot (or do not want) to add a new library, you can do this by the old way:
<h:selectOneRadio value="#{myBean.myValue}" ... onclick="this.form.submit();" valueChangeListener="#{myBean.doSomething}">
...
</h:selectOneRadio>
This code will submit the form where the radio button are contained when the onclick Javascript event is detected. On the server side, the action doSomething will be executed.
In this method, you can make a navigation rule to be executed:
public void doSomething(ValueChangeEvent evt) {
// Your code goes here...
...
// Now, we move to another page...
FacesContext context = FacesContext.getCurrentInstance();
NavigationHandler navigation = context.getApplication().getNavigationHandler();
navigation.handleNavigation(context, "", "some-outcome");
}
where some-outcome is an outcome defined in a navigation rule in your faces-config.xml.
With JSF 2.0 you can do the following
<h:selectOneRadio ...
...
<f:ajax event="change" render="#form" />
</h:selectOneRadio>
Related
I have an issue with making a menu in my project using Primefaces. Actually, this menu will get me a possibility to show some small dialogs with settings for the workspace (by clicking on menu items). Each dialog should have data lazy loading from database. Unfortunately, when I include my dialogs in the page (single xhtml file or a couple xhtml files with ui:include), an event onShow happens on each page reload and this is wrong and provoke too many unnecessary requests to the database.
Here is an example:
UI part
<h:form id="form1">
<p:menubar id="mainMenu">
<p:submenu label="Main menu" icon="ui-icon-document">
<p:menuitem value="My settings" onclick="mySettingsWv.show()" url="#" />
</p:submenu>
</p:menubar>
</h:form>
<p:dialog id="mySettingsDlg" header="My Settings" widgetVar="mySettingsWv" resizable="false"
closable="true" modal="true" showEffect="fade" hideEffect="explode" dynamic="true"
closeOnEscape="true" onShow="#{mybean.onShow()}">
<h:outputLabel value="Settings dialog" />
</p:dialog>
ManagedBean part:
#ManagedBean (name = "mybean")
#ViewScoped
public class MyBean {
public static Logger log = Logger.getLogger(MyBean.class);
public void onShow() {
log.info("Method onShow is being called on each page reloading, but dialog still has not been shown");
}
}
If I use action "onclick" for <p:menuitem> for manual calling the necessary method, it still executes it for each page reloading. Also if I try use actionListener, action attributes it don't work. <p:ajax> cannot be attached to <p:menuitem>.
What should I do in that case? What is wrong can be in my code?
Have a look at the primefaces documentation for p:dialog (same problem with p:menuitem and onclick). There the documentation says about onShow:
Client side callback to execute when dialog is displayed. (emphasis added)
That means that you can specify a javascript function there, but it does not work that way to specify a action on your backingbean which is called everytime the dialog is shown. What happens in your case is the following: #{mybean.onShow()} is evaluated only when the file is parsed (i.e. the p:dialog is rendered into the HTML) and then the value which is returned by the method is inserted there (i.e. the empty String).
To fix this you have to define a javascript callback which makes the call on the bean. You can do this by using p:remoteCommand:
<p:remoteCommand name="onShow" action="#{mybean.onShow}"
partialSubmit="true" process="#this"/>
And then specify this callback as the onShow attribute:
<p:dialog id="mySettingsDlg" ...
onShow="onShow()">
This is the situation:
I have a popup box to select one of the item listed(click the showParentAssetSearchButton) . Once selected the value of the selected item will be display in the main screen. In the main screen, there will be a button to clear up the item that selected. It will trigger an ajax action to the managed bean to clear the binding value(via click clearParentAssetButton).
When i do debugging, the value is clear and will not show in the main screen. However when i click on the save button, i notice that the property that should be empty is not actually empty. It still keep the value.
Following is the snippet UI code:
<h:panelGroup id="myregion">
<p:inputText id="parentAsset"
ondblclick="parentAssetDlg.show()"
value="#{assetMasterCreatePage.parentAsset.shortName}"
rendered="#{not empty assetMasterCreatePage.parentAsset}"/>
</h:panelGroup>
<p:commandButton icon="ui-icon-search"
id="showParentAssetSearchButton"
type="button"
title="#{msg.label_asset_search_parent_asset}"
onclick="parentAssetDlg.show()" />
<p:commandButton icon="ui-icon-trash"
id="clearParentAssetButton"
title="#{msg.label_asset_clear_parent_asset}"
actionListener="#{assetMasterCreatePage.doResetParentAsset}"
immediate="true"
process="#form"
update="clearParentAssetButton, myregion"
disabled="#{empty assetMasterCreatePage.parentAsset}" />
........
<p:commandButton value="#{msg.button_save}" icon="ui-icon-disk"
action="#{assetMasterCreatePage.doSaveAsset}" />
This is the managed bean snippet
#ManagedBean(name="assetMasterCreatePage")
#ViewScoped
public class AssetMasterCreatePage extends DefaultAssetMasterPage {
private AssetMaster assetMaster;
private AssetMaster parentAsset;
..........
.........
public void doResetParentAsset(){
parentAsset = null;
}
public String doSaveAssetMaster(){
assetMaster.setParentAsset(parentAsset);
assetMasterService.save(assetMaster);
MessageUtils.saveSuccessMessage();
return "save";
}
}
As you can see, when the button of the clearParentAssetButton is click, it will trigger ajax action #{assetMasterCreatePage.doResetParentAsset} to reset the value of the parentAsset. The issue here is when saving, the parentAsset which already should be null is not null.
I am using JSF 2 to perform the tasks.
Strange, is there any other fields which hold the value of parentAsset, I mean's in the page, have some fields like
<h:inputText value="parentAsset.shortName"/>, when you click the save button, a new parentAsset is initialized and saved, and also you can debug it and see the parentAsset's hash code to make sure whether the same one.
JFS1.2 + Richfaces 3.3
Situation is as follows:
JSP page renders conditionally one or another panelGroup.
Within each panelGroup there are couple setters and one command button.
Each of two panelGroups uses own bean for setting and performing action.
On the top of a page there's selectOneRadio with (obvious) two items - coresponding tow options of conditional rendering.
Page renders properly, switcher causes to render appropriate panel.
Case is, commands buttons doesn't call an action.
I know what's going on - when I click a button to call action dom is regenerated, but the value that hold my decision to display particular panel doesn't exist anymore. The button is not recreated, action is not fired.
Technically:
<h:selectOneRadio value="#{reportType}">
<f:selectItem itemLabel="x" itemValue="x"/>
<f:selectItem itemLabel="y" itemValue="y"/>
<a4j:support event="onclick" reRender="xPanel, yPanel/>
</h:selectOneRadio>
<h:panelGrid id="xPanel "columns="2" rendered="#{reportType eq 'x'}">
<...some setters>
<... commandbutton>
</h:panelGrid>
<h:panelGrid id="yPanel "columns="2" rendered="#{reportType eq 'y'}">
<...some setters>
<... commandbutton>
</h:panelGrid>
Question is, how to design the page to obtain proper rendering and actions?
For now, I created additional session bean that holds switching value (x|y), but that desing smells bad for me...
RichFaces 3.3 offers the <a4j:keepAlive> tag which does basically the same as Tomahawk's <t:saveState> and JSF2 #ViewScoped. Add the following line somewhere in your view:
<a4j:keepAlive beanName="#{bean}" />
This will keep the bean alive as long as you're returning null or void from action(listener) methods.
See also:
JSF 1.2: How to keep request scoped managed bean alive across postbacks on same view?
I will try to be as brief as possible, please stay with me here
"A.jsf" -> managed bean : bean
"#{bean.list}": will take us to B.jsf
<p:growl id="msgs" showDetail="true"/>
<h:form id="myform1" enctype="multipart/form-data">
<p:panel header="Upload" style="font-size: 11px;">
<h:panelGrid columns="2" cellpadding="10">
<h:outputLabel value="Drawing:" />
<p:fileUpload fileUploadListener="#{bean.handleFileUpload}" update="msgs" allowTypes="*.*;"/>
</h:panelGrid>
<p:commandButton ajax="false" immediate="true" id="back" value="Back" action="#{bean.list}"/>
<p:commandButton ajax="false" id="persist" value="Persist" action="#{bean.handleRevision}" />
</p:panel>
</h:form>
Then the handleFileUpload()
if(!upload){
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "You do not have permission to upload.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
...
"B.jsf" -> managed bean: bean2
...
<p:growl id="msgs" showDetail="true"/>
...
When I click upload, it give me a growl error message "You do not have permission to upload.", which is good. But then when I click "Back", which will take me to B.jsf, I see the growl message "You do not have permission to upload." again. What seem to be happening is as I click the "Back", I send other form request to upload, which then generated the same error message, which then being displayed at B.jsf. Is there a way to fix this, beside putting the "Back" button into an empty form, because now I have two buttons standing on top of each others, instead of side by side. I try to do this:
FacesContext.getCurrentInstance().addMessage("tom", msg);
hoping that it would send to component with id="tom", so then the growl with id=msgs, would not get load, but no luck. I try to turn the upload flag on when I click the Back button, but the web form get requested before the method that handle the back navigation get called.
It is not as brief as I want it to be, therefore I want apologize for it :D
beside putting the "Back" button into an empty form, because now I have two buttons standing on top of each others
The HTML <form> is by default a block element. HTML block elements are by default been placed in a new line. You actually want to make it an inline element. You can do this using display: inline; in CSS.
Back to the actual problem, it however surprises me that the fileUploadListener method is called in spite of the immediate="true" in the p:commandButton. I tried to reproduce this and I can confirm this. But I wouldn't expect it to happen. Normally the immediate="true" on a button is the solution to skip submitting of the "whole" form (at least, skip the UIInput components without this attribute). Further investigation learnt me that the p:fileUpload isn't an UIInput component at all and that the listener is fired during apply request values phase instead of validations or update model values phase. So this behaviour is fully predictable, but imo still an oversight in the design.
Since the p:fileUpload requires ajax="false" on the p:commandButton component, you can on the other hand also just remove it from the back button so that it fires an ajaxical request and hereby skips the fileUploadListener being called.
Actually, putting the button in a different form sounds like an excellent solution. The reason the buttons don't align any more is that the new starting <form> element starts on its own line. You should be able to prevent this by adding form { display: inline; } to your CSS file.
That said, if you have some leftover error messages that you want to get rid of, you can do this in the initializing method of your backing bean (if you have one). The following works peachily:
public void clearErrorMessages() {
//it may get messy to debug why messages are swallowed
logger.debug("clearing messages, coming from " + new Exception().getStackTrace()[1]);
Iterator iter = FacesContext.getCurrentInstance().getMessages();
while (iter.hasNext()) {
FacesMessage msg = (FacesMessage) iter.next();
logger.debug("clearing message: " + msg.getDetail());
iter.remove();
}
}
The disadvantage here is that any errors that occur between submitting the form and initializing the backing bean of the target page are also swallowed.
My goal is to dynamically load the contents of a component in JSF 2.0. The use case is this: user clicks some button, which opens a modal panel with some heavy-contents via AJAX. Due to its' heaviness, I want to delay loading it until/if user actually needs it. If the user closes this panel, it is not actually removed from DOM, just faded out. If the user clicks the initialization button again, the previously loaded panel is shown.
I know that I can prevent rendering of contents using rendered="#{cc.attrs.visibilityState == 'hidden'}" and that I can re-render the component via JSF AJAX call. However, how can I adjust the attributes of a composite component on-the-fly so that the second time around the component would actually render?
1) I know that I could do:
<h:outputLink>Foo
<f:ajax event="click" render="theComponentIWantToUpdate" listener="#{someBean.someMethod()}" />
</h:outputLink>
And then programmatically adjust theComponentIWantToUpdate attributes (to change value of #{cc.attrs.visibilityState}) so that it would actually render with full contents. But how to actually do that?
2) Also, the problem is that I don't want to update (re-render) theComponentIWantToUpdate each time the button is pressed, only the first time (see the business case). How can I set an evaluation for <f:ajax /> call for this? It has the disabled attribute, but it only orders whether or not to actually render the AJAX-handler (not evaluated each time the link is pressed).
3) Furthermore, I probably want to do some custom javascript first when the link is clicked and only execute AJAX request via javascript using jsf.ajax.request(). However, that function doesn't support providing listener attribute so I don't how to execute a backing bean method with raw javascript jsf.ajax.request() call? There is actually a similar question without suitable answers (see JSF 2.0 AJAX: jsf.ajax.request to call method not only rerender an area of page).
A partial solution:
Here is my link that sends an AJAX-request (inside a composite component):
<h:form>
<h:outputLink styleClass="modlet-icon">
<f:ajax event="click" render=":#{cc.clientId}:modalWindow:root" listener="#{modalWindowBean.enableContentRendering(cc.clientId, 'modalWindow')}" />
</h:outputLink>
</h:form>
The listener calls this method:
public class ModalWindowBean {
...
public void enableContentRendering(String clientId, String windowId) {
UIComponent component = FacesContext.getCurrentInstance().getViewRoot().findComponent(clientId + ":" + windowId);
component.getAttributes().put("contentRenderingEnabled", true);
}
}
Here is my target to be rendered:
<modalWindow:modalWindow id="modalWindow">
<quickMenu:quickMenuOverlay id="quickMenuOverlay" />
</modalWindow:modalWindow>
ModalWindow simply wraps the target into a nice looking window panel. Within ModalWindow:
<composite:implementation>
<h:outputScript library="component/modalWindow" name="modalWindow.js" target="head" />
<h:outputStylesheet library="component/modalWindow" name="ModalWindow.css" />
<h:panelGroup id="root" layout="block" styleClass="modalWindow hide">
<ui:fragment rendered="#{cc.attrs.contentRenderingEnabled}">
...all the wrapping elements with <composite:insertChildren /> within it
<script type="text/javascript">
// Fade it in
var win = ModalWindow.getInstance('#{cc.clientId}'); // this gets the instance, available everywhere
win.position(#{cc.attrs.left}, #{cc.attrs.top});
win.resize(#{cc.attrs.width}, #{cc.attrs.height});
win.fadeIn();
</script>
</ui:fragment>
</h:panelGroup>
<ui:fragment rendered="#{!cc.attrs.contentRenderingEnabled}">
<script type="text/javascript">
// Initialize modalWindow when it is rendered for the first time
var win = new ModalWindow('#{cc.clientId}'); // will be publicly available through ModalWindow static methods
</script>
</ui:fragment>
</composite:implementation>
The problem? AJAX-request is sent each time user clicks the button (so the window is reloaded and faded in each time). I need to be able to control when/if the AJAX-request is actually sent.
All this stuff makes me miss Apache Wicket, although I'm not sure how I would do this with it anyway :)