Showing posts with label Richfaces. Show all posts
Showing posts with label Richfaces. Show all posts

Thursday, January 28, 2016

Throw ValidatorException in JSF Validator

When throwing exception from a validator,
remember to throw ValidatorException instead of FacesException,
else the message component might be not able to display the correct validation message.

public void validAbc(FacesContext context, UIComponent component, Object value) {

   // some validation logic
  if(value.equals("abc")) {
    // proceed 
  } else {
    throw  new ValidatorException(new FacesMessage(
        FacesMessage.SEVERITY.ERROR, null, "validation error message"));
  }
}



Done!!

Tuesday, December 29, 2015

How to parameterized label from resource bundle

Assuming we have a of labels to be displayed by type.
label.type.a = This is label A label.type.b = This is label B label.type.c = This is label C label.type.d = This is label D

To display the label by type in xhtml, the simplest way it to use a rendered attribute
<h:outputLabel value="#{lbl['label.type.a']}" rendered="#{myType == 'A'}" /> <h:outputLabel value="#{lbl['label.type.b']}" rendered="#{myType == 'B'}" /> <h:outputLabel value="#{lbl['label.type.c']}" rendered="#{myType == 'C'}" /> <h:outputLabel value="#{lbl['label.type.d']}" rendered="#{myType == 'D'}" />

Instead of using the above sample, I would prefer to use two lines to achieve the same effect.
especially when the list of type are long. 
<ui:param name="typeLabel" value="label.type.#{myType}" /> <h:outputLabel value="#{lbl['typeLabel']}" />


Done!!

Monday, June 29, 2015

How to set common styleClass when component is required, readonly or disabled

This is to show how to highlight input components globally when it is either required, readonly, or disabled.

1. Create a class that is extending the javax.faces.application.ViewHandlerWrapper.
public class MyViewHandlerWrapper extends ViewHandlerWrapper {

}

2. Overrider the renderView method.
@Override
public void renderView(FacesContext fc, UIViewRoot view) throws IOException, FacesException {

  super.renderView(fc, view);

}

3. create a private method to find input components recursively and highlight them based on the required, readonly and disabled attribute.

Tuesday, May 5, 2015

Loop every components in a ViewRoot recursively

1. Writing the recursive method.
private void loopComponentsRecursively(List<UIComponent> childrenList) {
  for(UIComponent component : childrenList) {
   if(component.getChildCount() > 0) {
    loopComponentsRecursively(component.getChildren());
   } else {
    // no more children for this component
    System.out.println("child: " + component.getId() + "  " + component.getClientId());
   }
  }
}

2. Invoking the recursive method
// some code
loopComponentsRecursively(viewRoot.getChildren());
//some other code


Done!!

Saturday, May 17, 2014

How to integrate SlidesJS into JSF2

SlidesJS is an image slider that is nice and easy to implement.
To implement SlidesJS into JSF2.x application, just need to download the required files and follow the steps below.

1. copy all the required files into resources folder.

Tuesday, March 4, 2014

How to resolve jQuery conflict in Liferay

In some cases, we need to install jQuery in Liferay especially the custom theme to achieve some UI features.
But that could be conflict with jQuery that come along with custom portlet.
eg, RichFaces portlet, PrimeFaces portlet, IceFaces portlet.

as long as we add the following line of code in Liferay theme,
then the conflict could be resolved.

jQuery.noConflict(true)


Done!!

Sunday, March 2, 2014

How to pass parameters with <a4j:jsFunction />

<a4j:jsFunction /> allowed us to send JSF ajax request with javascript function.

sample
<a4j:commandButton
    value="TEST"
    action="#{myBean.action}"
    oncomplete="myJsFunction();" />


<a4j:jsFunction name="myJsFunction" action="#{myBean.jsAction}" />


But the above implementation has a limitation,
where not allowed us pass parameter(s) to #{myBean.jsAction}

This issue could be resolved by adding <a4j:param /> under <a4j:jsFunction />
The <a4j:param /> associates to a property in managed bean, and inject the param value into managed bean before the action being fired.
Thus, the action (#{myBean.jsAction}) can get the param1 value from the getter.

Monday, January 27, 2014

Loading Velocity template in JSF

When loading Velocity template with the default setting.
The following exception might be hit
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource

Even I used the Class Resource Loader, still hitting the same exception.

The exception solved when used File Resource Loader together with the system Real Path.
String myTemplatePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/WEB-INF/mytemplatepath");

Properties p = new Properties();
p.setProperty( "file.resource.loader.path", myTemplatePath);
Velocity.init(p);

Template template = Velocity.getTemplate( "mytemplate1.vm" );

p/s: assuming all .vm files are kept under <webapp>/WEB-INF/mytemplatepath folder.

Done!!

Saturday, November 2, 2013

How to invoke action before a view is rendered

There is a new component since JSF2.0 & JSF2.1 that can invoke a listener at the defined type of JSF event.
If is <f:event />

To invoke action/listener before a view is rendered,
The type event to be used is preRenderView
and this event type is available since JSF2.1

eg,
<f:event type="preRenderView" listener="#{myBean.preRenderViewListener}" />

with the above sample code, #{myBean.preRenderViewListener} will be invoked before the view is rendered.

Thursday, October 24, 2013

Looping in JSF dataTable

To build a dataTable with dynamic columns in RichFaces,
we may use <c:foreach /> or <rich:columns /> in <rich:dataTable />
<rich:dataTable var="var" value="#{myBean.list}">
    <c:foreach var="column" value="#{myBean.columns}">
        <rich:column>
            <f:facet name="header">
                <h:outputLabel value="#{column.name}" />
            </f:facet>
            <h:outputLabel value="#{var[column.value]}" />
        </rich:column>
    </c:foreach>
</rich:dataTable>

But the same is not applicable in <p:dataTable />
because <ui:repeat /> and <c:foreach /> is not working in <p:dataTable />
Thus, the only solution to achieve dynamic column in <p:dataTable /> is to use <p:columns />
<p:dataTable var="var" value="#{myBean.list}">
    <p:columns var="colomn" value="#{myBean.columns}">
        <f:facet name="header">
            <h:outputLabel value="#{column.name}" />
        </f:facet>
        <h:outputLabel value="#{var[column.value]}" />
    </p:columns>
</p:dataTable>

With <c:foreach /> or <ui:repeat />, more flexibilities could be achieved.
Since they are not working in <p:dataTable />, the only way to achieve looping is <p:columns /> with less flexibilities.


Done!!

Monday, October 21, 2013

Accessing bean's property dynamically like a map

Assuming we have the following class
@ManagedBean(name="myBean")
public class MyBean {
    private String property1;
    private String property2;

    // getter and setting for property1, property2, ...
}

Normally we are accessing the properties in a bean from xhtml like syntax below.
#{myBean.property1}

But, recently found that we can actually accessing the properties of a bean like accessing a map.
#{myBean['property1']}

#{myBean['property2']}

in normally circumstances, it is nothing special from the traditional way.
But it is relatively useful if we want to dynamically access the properties in a bean.


Done!!

Wednesday, September 25, 2013

How to retrieve logged in user model in JSF2 Portlet

Retrieving logged in user is essential in every system, especially for logging purpose or authentication and authorization.

Steps to retrieve Liferay Logged in user in JSF portlet:
1. get the PortletRequest from JSF context
    PortletRequest portletRequest = (PortletRequest) FacesContext                                                                 .getCurrentInstance()
                                .getExternalContext().getRequest();

2. get the logged in user id
    String userId = portletRequest .getRemoteUser();

3. get the user model with Liferay API
    User user = UserServiceUtil.getUserById(Long.valueOf(userId));


Done!!

Saturday, August 17, 2013

How to display meaningful element name when exception

During form validation in JSF, by default exception(s) thrown will display the element's client id. 

But that is meaningless to the system users, because the client id is not tally with the corresponding element label. 

Thursday, June 6, 2013

Authorization in JSF with Facelets View Handler

According to wikipedia, authorization is the function of specifying access rights to resources.
Authorization is important to protect sensitive against different users.

The simplest way is to provide the access right to the targeted fields/components directly
for readOnly access,
<h:outputText id="authorizedId" value="#{bean.authorizedValue}" readonly="#{bean.authorizedReadonly}" />

for viewable access,
<h:outputText id="authorizedId" value="#{bean.authorizedValue}" disabled="#{bean.authorizedDisabled}" />

but the above solution is NOT feasible if there are many pages and fields/components to be authorized;
NOT flexible, if there are access right changes, re-coding is required.

Another feasible way is through FaceletsViewHandler.
In JSF with Facelets view handling, we can actually place all the authorization controls to the FaceletsViewHandler as the control central.

Sunday, June 2, 2013

Richfaces oncomplete not working in Liferay

The oncomplete attribute is a very common and useful in RichFaces application to invoke a javascript function after calling a server side action.

<a4j:commandButton value="Some Action" action="#{testBean.someAction}" oncomplete="oncompleteScript" />

But this attribute is ignored in RichFaces portlet in Liferay.

The root cause is the Liferay portlet bridge.
When we create RichFaces 4 portlet in Liferay with Liferay IDE, it comes with the default Liferay jar (bridge-api, bridge-impl, portal, util)

The version of Liferay portlet bridge bundled with the Liferay IDE causing the oncomplete attribute being ignored.

JSF number validator with regular expression

Although we can use <f:validateLongRange /> and <f:validateDoubleRange /> to validate number in JSF, but  that are simple enough and unable to validate complex number format.

To be able to validate more complex number, regular expression is recommended.
The core idea is to create a facelets composite component from <f:validateRegex /> validator by providing default regular expression to validate desired number format.

some useful number regular expression in the table below
FormatRegular expression
number with comma^(\d|,)*\.?\d*$
positive number only^\d{1,7}$
Percentage ^(0*100{1,1}\.?((?<=\.)0*)?%?$)|(^0*\d{0,2}\.?((?<=\.)\d*)?%?)$
currency^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$
for more information about number regular expression, please refer here.

Now let's start building the number validator with the chosen regular expression.

Wednesday, May 15, 2013

Simple number validation in JSF

There are many ready validator in JSF, eg. <f:validateLongRange />, <f:validateDoubleRange />, <f:validateRegex />, etc.
for more information about JSF validator, please refer here.

to validate number value, we can use the ready made JSF validator, that is <f:validateLongRange /> and <f:validateDoubleRange />

Sample code:
managedBean
private String longValue;
// getter & setter for longValue

private String doubleValue;
// getter & setter for doubleValue;

Thursday, May 9, 2013

How to create custom taglib descriptor in a JSF project

A taglib descriptor in JSF is a taglib.xml.
Name the taglib descriptor always start with a word and follow by "taglib.xml", eg. kian.taglib.xml
taglib descriptor allowed us to define our custom namespace, convertor, validator, composite component, and facelets function.
more details about taglib descriptor could be found here.

Thursday, April 11, 2013

How to create Credit Card Validator with Facelets

This post shows how to build a custom JSF regex validator to validate Credit Card number with Facelets.

There are different types of Credit Cards, the regex used to validate different types of Credit Card are vary with the types of Credit Card.
Visa ^4[0-9]{12}(?:[0-9]{3})?$
Master Card ^5[1-5][0-9]{14}$
American Express ^3[47][0-9]{13}$
Diners Club ^3(?:0[0-5]|[68][0-9])[0-9]{11}$

For more information about Credit Card Regex, please refer here.
so now let's start to build the Credit Card validator.

Tuesday, April 9, 2013

Easy JSF Email validator with Facelets

This post shows how to build a custom JSF regex validator to validate email address with Facelets.
Building email validator with Facelets is very easy if compare to building email validator with JSF component classes.

Steps:
1. create the validateEmail.xhtml in folder <WebContent>/views/validator
    Regex here could be changed to any desired format.

<ui:composition
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html">
    <f:validateRegex
        pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />

</ui:composition>

LinkWithin

Related Posts Plugin for WordPress, Blogger...