Showing posts with label Primefaces. Show all posts
Showing posts with label Primefaces. Show all posts

Wednesday, April 12, 2017

How to get HTML element from PrimeFaces

In some scenarios, we might want to get the HTML element of a PrimeFaces component and process in javascript.
Assume we have a PrimeFaces inputText component like below.


<p:inputText id="address" value="#{myBean.address}" widgetVar="addrWV" />



1. widgetVar

addrWV.jq.get(0);



2. #{p:component('compId')}

document.getElementById('#{p:component(&quot;address&quot;)}');




Done!!

Tuesday, August 2, 2016

PrimeFaces fileUpload javascript properties

fileuplaod_wgt.buttonBar.find("button.cancel")
fileuplaod_wgt.buttonBar.find("button.start")
fileuplaod_wgt.buttonBar.find('input[type=file]')

upload content
upload.uploadContent'

number of uploaded files
var files = fileuplaod_wgt.uploadContent.find('.files .template-upload');

invalid files
fileuplaod_wgt.uploadContent.find("tr.ui-state-error");



reference:
http://stackoverflow.com/questions/14881131/primefaces-upload-how-to-only-allow-one-upload-in-advance-mode

Monday, June 27, 2016

How to disable Choose button in PrimeFaces fileupload component


The javascript function is to disable "Choose" button in <p:fileUpload /> component a file has been uploaded.
It is applicable to PrimeFaces 3.5

function below will find the Choose button from the passed in widgetVar when the file component onchange,
if the number of uploaded files more than 1,
disable the Choose button.


<script type="text/javascript">

    function onchangeDisableChooseBtn(upload_widget_var) {
        if(upload_widget_var.buttonBar.find('input[type=file]').get(0).type == 'file') {
            upload_widget_var.buttonBar.find('input[type=file]').change(function() {
                var files = upload_widget_var.uploadContent.find('.files tr');
                if (files.length >= 1) {
                    upload_widget_var.buttonBar.find('input[type=file]').get(0).disabled=true;
                }
                onchangeDisableChooseBtn(upload_widget);
            });
        }
    }

</script>



Done!!

Wednesday, June 22, 2016

How to hide icons in PrimeFaces fileUpload component.

PrimeFaces version: 3.5

to hide icon in choose button

  .fileupload-buttonbar .fileinput-button .ui-icon-plusthick{
         display: none !important;
 }


to hide icon in upload button

 .fileupload-buttonbar .start .ui-icon-arrowreturnthick-1-n{
         display: none !important;
 }


to hide icon in cancel button


 .fileupload-buttonbar .cancel .ui-icon-cancel{
         display: none !important;
 }




Done!!

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!!

Wednesday, January 6, 2016

Simple Captcha by PrimeFaces graphicImage

Basically the concept is to generate random text and display it with image, which is <p:graphicImage />.

1. Write a method to generate the StreamedContent.
public StreamedContent getCaptcha() {
    StreamedContent 2dText = null;
    try {
        BufferedImage bufferedImg = new BufferedImage(
                100, 25, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bufferedImg.createGraphics();
        
        String captchaText = generateRandomString();            
        
        g2.drawString(captchaText, 0, 10);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImg, "png", os);
        2dText = new DefaultStreamedContent(
                new ByteArrayInputStream(os.toByteArray()), "image/png"); 
    } 
    catch (Exception e) {
        e.printStackTrace();
    }
    return 2dText;
}


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!!

Saturday, October 24, 2015

getElementById with PrimeFaces

To get a HTML component in javascript, normally we use getElementById('componentId'),
But there are 2 constraints to get PrimeFaces component.

1. the id defined in component tag is not the actual element id in HTML.
to resolve this issue, we can use the javascript API provided by PrimeFaces to retrieve the actual HTML element id.
#{p:component('componentId')}

2. quote in the above API breaks the quote in getElementById
to resolve this problem, the quote in PF's API need to be replaced.

document.getElementById('#{p:component(&quot;componentId&quot;)}')


Done!!

Tuesday, August 18, 2015

How to customize date display in PrimeFaces Calendar component

There is a scenario where the requirement wants the calendar component to enable certain date only.
eg, enable 1st day of the month only.

To achieve this requirement, attribute beforeShowDay need to be used.
Description for beforeShowDay in PrimeFaces tag document.
Callback to execute before displaying a date, used to customize date display.

Steps:
1. Write the callback function to be called by the Calendar component.
function beforeShowDayCallback(date){
  if (date.getDate() == 1) {
    return [true, ''];
  }
  return [false, ''];
}

2. Call the function in calendar component.
<p:calendar id="gstEffDateId"  beforeShowDay="beforeShowDayCallback"  />


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, February 28, 2015

p:tabMenu model does not work with JSF 2.1.x

According to PrimeFaces demo page, <p:tabMenu /> is working with <p:menuItem /> to display tab content.
<p:tabMenu /> also works with model to display tab content.

<p:tabMenu activeIndex="#{backingBean.tabActiveIndex}"
    model="#{backingBean.tabModel}" />

But <p:tabMenu /> not working with some of the JSF2.1 distribution.
eg, JSF2.1.19, JSF2.1.22, JSF2.1.29, etc

When tabMenu with model running with JSF2.1.29. some of the tabs are not able to click.

The only solution to resolve this problem, is to use <p:menuItem /> instead of model.


Done!!

Tuesday, October 28, 2014

How to disable row selection in PrimeFaces datatable

This is not a official/proper way to disable the row selection in <p:dataTable />
But a workaround since there is no way to disable the row selection at the moment.

assuming we have the following dataTable.
<p:dataTable
    value="#{myBean.resultList}"
    selection="#{myBean.selection}"
    var="var"
    ..... />

    <p:column selectionMode="multiple" />
    <p:column .... />

</p:dataTable>

To disable row selection in the above <p:dataTable />
we need to add <p:ajax /> into the <p:dataTable />

Wednesday, October 22, 2014

How to set max date and min date in <p:calendar />

The maxdate and mindate attribute is extremely useful for setting available date range for user selection.

e.g.
-Expiry date of an item should not be less than today.
-Date of birth should not be future date.

So how to set maxdate and mindate in PrimeFaces calendar component?

1. create the java.util.date object in backingBean
private Date currentDate = new Date();

public Date getCurrentDate() {

    return currentDate;
}

2. set the java.util.date object as mindate or maxdate
<p:calendar value="#{bean.expiryDate}" mindate="#{bean.currentDate}" />
 

<p:calendar value="#{bean.birthDate}" maxdate="#{bean.currentDate}" />


Done!!

Tuesday, October 21, 2014

How to display dynamic PDF document with <p:media /> component

From the PrimeFaces showcase, the media component used to display PDF document
But the showcase uses a static PDF document.

In real life, we might want to display different PDF documents by different use cases,
or a runtime generated PDF document.

To achieve the above purpose, we need to use the value attribute in <p:media /> component by passing in a StreamedContent from backingBean.

1. BackingBean method that return StreamedContent.
public StreamedContent getPdfDocument() {  

     // logic to generate the PDF  

    return new DefaultStreamedContent(pdfInByteArrayInputStream, "application/pdf");
}


2. display the PDF content with <p:media /> component.

<p:media value="#{myBean.pdfDocument}" width="100%" height="500px" player="pdf" />


Done!!

Wednesday, August 27, 2014

How to define Default Action in PrimeFaces

This is to define what action to be executed when the "Enter" is press.

There is easy-to-use component in PrimeFaces to get this done.


<p:defaultCommand target="btn2" />

<p:commandButton id="btn1" action="#{myBean.action1}" />
<p:commandButton id="btn2" action="#{myBean.action2}" />
<p:commandButton id="btn3" action="#{myBean.action3}" />

with the above code, when user press on "Enter", action to be executed is #{myBean.action2} that bind to <p:commandButton id="btn2" />


Done!!

Sunday, June 8, 2014

How to show wider year range in PrimeFaces Calendar

By default, the year range is 10 years before and 10 years after.

as shown above, this year is 2014, the year range can only in between 2004-2024.

to display wider range, need to enable the yearRange attribute.

<p:calendar id="pfc1"
    yearRange="c-50:c+10"
    showOn="button"
    navigator="true" />

with the above yearRange settings, the year can display up to 50 years before and 10 years after.
Meaning current year -50 and current + 10.


Done!!

Monday, May 26, 2014

How to invoke javascript from Managed Bean in PrimeFaces

In PrimeFaces, we can invoke a javascript function from managed bean.
One of the good example is to keep dialog open when validation exception.

Besides, other javascript function can be called.
code in xhtml

<p:commandButton value="Call JS from MB" action="#{myBean.callJsFromMB}" />

code in managed bean

public void callJsFromMB() {
    // other business logic or validation
    RequestContext.getCurrentInstance().execute("alert('test')");
}


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.

LinkWithin

Related Posts Plugin for WordPress, Blogger...