JSF RichFaces - How to show a rich:modalPanel when page loaded? - spring

That's exactly what I am looking for ... I need to show a rich:modalPanel automatically when the page has ended loading.
This is my approach so far:
MAIN.XHTML
<script type="text/javascript">
function openPopUp(){
if(#{rich:element('popUpAltaTrenesEstaciones')}.value == 'true'){
#{rich:component('idAltaPlantillasTrenesEstacionesPop')}.show();
return false;
}
}
</script>
.........
<a4j:include id="popUp" viewId="AltaPlantillasTrenesEstacionesPopUp.xhtml" />
.....
<a4j:outputPanel ajaxRendered="true">
<h:inputText id="popUpAltaTrenesEstaciones"
value="#{altaPlantillasTrenesEstaciones.showPopUp}"
style="display:none;" />
</a4j:outputPanel>
BACKING BEAN. JAVA
private boolean showPopUp;
#PostConstruct
public void init() {
...
setShowPopUp(true);
}
POPUP.XHTML
<rich:modalPanel id="idAltaPlantillasTrenesEstacionesPop" height="200"
width="400" rendered="true">
<a4j:form>
........
</a4j:form>
</rich:modalPanel>
WHAT AM I DOING WRONG??? DO I NEED TO ADD ANYTHING ELSE?
THANK YOU

There is 'showWhenRendered' attribute or similar.

You might want to call the function openPopup() you have declared ...

Related

JSF 1.2 empty <h:selectManyListbox /> validation issue

I'm kind of new to JSF and I'm having trouble to understand what values JSF renders in a form after its validation fails. Im using WebSphere 7 and its default implementation of JSF, MyFaces (I think 2.0).
My xhtml looks like this:
<h:form id="form">
<h:inputText id="text" value="#{backing.text}" required="true"/>
<h:message for="text" />
<h:selectManyListbox id="options" value="#{backing.options}" required="true">
<f:selectItem itemLabel="1" itemValue="1" />
<f:selectItem itemLabel="2" itemValue="2" />
<f:selectItem itemLabel="3" itemValue="3" />
</h:selectManyListbox>
<h:message for="options" />
<h:commandButton value="Save" />
</h:form>
And my backing bean like this:
public class Backing {
private String text;
private String[] options;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String[] getOptions() {
return options;
}
public void setOptions(String[] options) {
this.options = options;
}
}
I fill the <h:inputText /> with some text.
I select two options from the <h:selectManyListbox />
I press the 'Save' button
The form is rendered with the value I entered for <h:inputText /> and with the options I selected on the <h:selectManyListbox /> (no validation messages are shown, as expected)
Now ...
I empty the <h:inputText />
I deselect the two options from the <h:selectManyListbox />
I press the 'Save' button
The form renders the <h:inputText /> empty and the <h:selectManyListbox /> with the previous options I had selected (both validation messages are shown, as expected)
As you can see, the behaviour when rendering the <h:inputText /> and the <h:selectManyListbox /> is different:
<h:inputText /> renders component's submitted value
<h:selectManyListbox /> renders bean's value
I've been trying to render <h:selectManyListbox /> with no options selected without hacking or messing my code, but had no luck.
¿Is this some bug? ¿Am I missing something?
The less hacky solution I found is to copy and re-implement the method renderOption, overriding the default MenuRenderer.
The original source is something like this as I had to decompile (version 1.2_13).
Notice that I'm pasting only the lines that actually need to be changed. If you need to use this solution you will have to copy the full contents of the method:
public class MenuRenderer extends HtmlBasicInputRenderer {
protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, HtmlBasicRenderer.OptionComponentInfo optionInfo) throws IOException {
(...)
Object valuesArray;
Object itemValue;
if (submittedValues != null) {
boolean containsValue = containsaValue(submittedValues);
if (containsValue) {
valuesArray = submittedValues;
itemValue = valueString;
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
(...)
}
}
I created CustomListboxRenderer (ListboxRenderer extends MenuRenderer) like this:
public class CustomListboxRenderer extends ListboxRenderer {
#Override
protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, HtmlBasicRenderer.OptionComponentInfo optionInfo) throws IOException {
(...)
Object valuesArray;
Object itemValue;
if (submittedValues != null) {
valuesArray = submittedValues;
itemValue = valueString;
} else {
valuesArray = currentSelections;
itemValue = curItem.getValue();
}
(...)
}
}
and then added in faces-config the next lines:
<render-kit>
<renderer>
<component-family>javax.faces.SelectMany</component-family>
<renderer-type>javax.faces.Listbox</renderer-type>
<renderer-class>CustomListboxRenderer</renderer-class>
</renderer>
</render-kit>

Autoupdate of primefaces component

What I have is this piece of xhtml Code:
<p:layoutUnit id="bottomline" position="south" gutter="0">
<h:outputText rendered=",#{not empty sprintlisteMB.getSaveStatus()}" style="float:left; color:white; font-size: 0.8em;" value="#{sprintlisteMB.getSaveStatus()}"/>
</p:layoutUnit>
sprintlisteMB.getSaveStatus() returns simply returns the String saveStatus. Now I want the outputText Component to refresh anytime saveStatus is changed.
I'm not quite sure how to implement something like that and i coudn't find anything that fits my needs.
Thanks for any help!
EDIT:
So now i have Something like this:
<p:layoutUnit id="bottomline" position="south" gutter="0">
<h:outputText style="float:left; color:white; font-size: 0.8em;"
value="#{sprintlisteMB.getSaveStatus()}" />
</p:layoutUnit>
<p:socket onMessage="handleChange" channel="/saveStatus" />
<script type="text/javascript">
function handleChange(data) {
$('.display').html(data);
}
...
package de.wdr.testtool.helfer;
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.impl.JSONEncoder;
#PushEndpoint("/saveStatus")
public class SaveStatusPushRecource {
#OnMessage(encoders = {JSONEncoder.class})
public String onChange(String status) {
return status;
}
}
...
public void setSaveStatus(final String status) {
saveStatus = status;
final EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish("/saveStatus", String.valueOf(saveStatus));
}
setSaveStatus is called from several beans anytime the changes on the database are made.
But right right now it still won't update the site. What's missing?

How to pass the value of <#spring.formSingleSelect..> to javascript?

How to pass the formSingleSelect vale to js function
<script type="text/javascript">
function myfunction(var id){
alert("hi"+id);
}
<#spring.formSingleSelect path="LoginIDForm.ID" options=userIDs attributes='onChange="myfunction();"'/>
I believe this will work:
<#spring.bind path="LoginIDForm.ID" />
<script type="text/javascript">
function myfunction(var id){
alert("hi" + id);
}
</script>
<#spring.formSingleSelect path="LoginIDForm.ID" options=userIDs
attributes='onChange="myfunction(\'${spring.status.expression}\');"'/>
Basically <#spring.formSingleSelect path="LoginIDForm.ID" /> is the shorthand of doing:
<#spring.bind path="LoginIDForm.ID" />
<select name="${spring.status.expression}">
</select>
${spring.status.expression} holds the value you need.

Struts2 AJAX validation doesn't stay on page

I've been trying for a few days now to make Struts2 AJAX validation work but I can't solve one last problem. I'm using the struts2jquery plugin to asynchronously submit my form:
<div id="result"></div>
<s:form action="RegisterUser" theme="xhtml" method="post">
<s:textfield key="firstname" label="First name" size="35"
required="true" />
<s:textfield key="lastname" label="Last name" size="35"
required="true" />
<s:textfield key="address" label="Address" size="35"
required="true" />
<s:textfield key="phone" label="Phone number" size="35" />
<s:textfield key="username" label="Username" size="35"
required="true" />
<s:password key="password" label="Password" size="35"
required="true" />
<s:textfield key="email" label="E-mail address" size="35"
required="true" />
<sj:submit key="Inregistrare" targets="result" align="right"
button="true" validate="true" onSuccessTopics="notifyRegistration" />
</s:form>
I've included the required scripts:
<script type="text/javascript" src="./js/registerScript.js"></script>
<!-- This files are needed for AJAX Validation of XHTML Forms -->
<script src="${pageContext.request.contextPath}/struts/utils.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/struts/xhtml/validation.js"
type="text/javascript"></script>
and the tag:
<sj:head jqueryui="true" />
The onSuccess handler:
$(document).ready(function(){
$.subscribe('notifyRegistration', function(event,data) {
var registrationStatus = event.originalEvent.data.registrationStatus;
if(registrationStatus == 'SUCCESS'){
alert('Contul dumneavoastra a fost creat cu success!');
window.location.href = "./index.html";
} else {
alert('Contul dumneavoastra nu a putut fi creat. Va rugam incercati din nou.');
}
});
});
My configuration looks like this:
<action name="RegisterUser" class="actions.Register" method="execute">
<interceptor-ref name="jsonValidationWorkflowStack"/>
<result name="input">/pages/Register.jsp</result>
<result type="json"/>
</action>
And the execute method of my action class:
public String execute() throws Exception {
if (isInvalid(getUsername()) || isInvalid(getPassword())
|| isInvalid(getEmail())) {
registrationStatus = REGISTRATION_ERROR;
}
if (registerUser()) {
registrationStatus = REGISTRATION_SUCCESS;
return SUCCESS;
}else {
registrationStatus = REGISTRATION_ERROR;
}
return SUCCESS;
}
The registerUser() method makes the actual insert into the database. The validation XML is called Register-Validation.xml.
The validation works fine - if some fields are not filled in, it shows the error labels without refreshing the page. My problem is that even is the action returns SUCCESS or ERROR, the browser displays the JSON that it sent back on another page, ../Register.action. I have no idea why it doesn't enter my onSuccess handler. I've successfully used AJAX on other forms, the only difference here is that I use the validation xml and the jsonValidationWorkflowStack interceptor. Why is this happening and how can I avoid being redirected? Why doesn't the request reach the onSuccess handler?
Do you have getters for registrationStatus in your Action ?
I would put an alert(event.originalEvent.data.registrationStatus); in your notifyRegistration callback function, just to see what is its value.
By the way, it seems that you have mixed
Struts2-jQuery Plugin AJAX Form Validation with Struts2 XHTML Theme
with
Struts2-jQuery Plugin: Remote Link that handle an JSON Result with an onSuccessTopic
AFAIK (but I've never used this specific kind of validation), the validation should not be handled in execute(), but in validate() or through XML, or with Annotations.
The example in Struts2-jQuery Plugin showcase uses Annotations, but you can easily transform it in XML and try the showcase.
You would have no need to use the javascript function nor the onSuccessTopic at all, following the example.
You can run it in the showcase too, under Forms -> Forms with Validation (but stick to the documentation for the code, because the code in the showcase seems to miss some pieces... for example the validation against "test" password).

SharePoint Web Part : Can't make a jquery ajax call to ashx handler

I have a scrollable GridView in my Web Part and I have to make an AJAX call on each user scroll. I use Jquery 1.7.1 in the web part to call a c# handler class.
I am getting error 500 : Internal Server Error.
Here is a sample of the ascx :
<div id="divProducts" style="height:300px;overflow:auto">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" EnableViewState="false">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle CssClass="header" BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
</asp:GridView>
</div>
<div id="divProgress" style="margin-top: -50px;margin-left:150px;z-index:-999">
<asp:Image ID="image1" ImageUrl="~/_layouts/images/MyWebPart/loading.gif" width="100" height="100" runat="server" />
</div>
<script type="text/javascript">
$(document).ready(function () {
//initially hide the loading gif
$("#divProgress").hide();
//Attach function to the scroll event of the div
$("#divProducts").scroll(function () {
//User has scrolled to the end of the grid. Load new data..
$("#divProgress").ajaxStart(function () {
$(this).show();
});
$("#divProgress").ajaxStop(function () {
$(this).hide();
});
BindNewData();
});
});
function BindNewData() {
$.ajax({
type: "GET",
url: "/_layouts/MyWebPart/FetchRecordsHandler.ashx",
success: function (data) {
alert('data ', data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
I added a ASHX file that will be deployed in Layouts folder of my web part project (Layouts/MyWebPart/FetchRecordsHandler.ashx) :
<%# WebHandler Language="C#" Class="MyWebPart.Code.FetchRecordsHandler" CodeBehind="FetchRecordsHandler.cs" %>
And I created the class FetchRecordsHandler that implements IHttpHandler with correct namespace :
namespace MyWebPart.Code
{
class FetchRecordsHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Write("From the handler at " + DateTime.Now);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
This method doesn't work in my web part. Any idea of a solution or maybe another technic to make ajax calls from the scroll events to the web part ?
Thx
You need to change your .ashx to something like:
<%# WebHandler Language="C#" Class="MyWebPart.Code.FetchRecordsHandler, {my assembly}, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx" %>
Where {my assembly} is the name of the compiled .dll (without the .dll), probably MyWebPart and xxxxxxxxxxxxxxxx is the public key token for your assembly. One way to find this would be to look at the deployed .ascx from your web part, the first line or so should contain something similar.
I imagine the 500 error you are receiving has something to do with the fact that SharePoint cannot load the assembly for your .ashx. You could look in the event viewer for more details.

Resources