EzDevInfo.com

primefaces interview questions

Top primefaces frequently asked interview questions

How to remove border from specific PrimeFaces p:panelGrid?

I have difficulty in removing border from a specific PrimeFaces <p:panelGrid>.

<p:panelGrid styleClass="companyHeaderGrid">
    <p:row>
        <p:column>
            Some tags
        </p:column>
        <p:column>
            Some tags
        </p:column>
    </p:row>
</p:panelGrid>

I have been able to remove border from the cells with:

.companyHeaderGrid td {
    border: none;
}

But

.companyHeaderGrid {
    border: none;
}

Does not work.


Source: (StackOverflow)

Can I update a JSF component from a JSF backing bean method?

Is there a way to have a JSF Backing bean cause an update of a component on the page? I am not looking to use an ajax component with update attribute to update a component on the page. I need to trigger an update from within a JSF backing bean method. Note the update on the page can happen after this method completes or prior to its completion. I am using PrimeFaces, if there is a solution that can be had from using PrimeFaces.


Source: (StackOverflow)

Advertisements

Mutually restricting begin and end date-times using p:calendar (no validation)

We have a requirement to present two p:calendar components to the user, representing a start and end date each. Both datetimes have dates, hours and minutes. PrimeFaces has perfect mindate, maxdate, minHour, maxHour, minMinute, and minMinute attributes available.

The requirement now is:

It is impossible to set the start datetime to anything greater than or equal to the end datetime. It is impossible to set the end datetime to anything less than or equal to the end datetime.

The following equation should hold true:

begin datetime < end datetime

Now we tried the following JSF:

<p:calendar id="begin-date"
            value="#{debugManager.selectedBeginDate}"
            mindate="#{debugManager.minBeginDate}"
            maxdate="#{debugManager.maxBeginDate}"
            maxHour="#{debugManager.maxBeginHour}"
            maxMinute="#{debugManager.maxBeginMinute}"
            pattern="yyyy-MM-dd HH:mm"
            showButtonPanel="true"
            readonlyInput="true"
            navigator="true"
            showOn="button"
            required="true">
    <p:ajax event="dateSelect" update="end-date" />
</p:calendar>

<p:calendar id="end-date"
            value="#{debugManager.selectedEndDate}"
            mindate="#{debugManager.minEndDate}"
            minHour="#{debugManager.minEndHour}"
            minMinute="#{debugManager.minEndMinute}"
            pattern="yyyy-MM-dd HH:mm"
            showButtonPanel="true"
            readonlyInput="true"
            navigator="true"
            showOn="button">
    <p:ajax event="dateSelect" update="begin-date" />
</p:calendar>

Here's an examplary min/max method (mindate of end-date):

public Date getMinEndDate()
{
    return this.getSelectedBeginDate();
}

As you can see, the minimum end date is the currently AJAX-selected begin date. Setting an end date correctly disallows setting the begin date past the end date.

The problems start when involving the time into the equation...

Since the interface of p:calendar has separate methods, the bean has to provide the logic:

public int getMinEndHour()
{
    Date selectedBeginDate = this.getSelectedBeginDate();
    Date selectedEndDate = this.getSelectedEndDate();

    if ( selectedBeginDate != null && DateUtil.isSameDay( selectedBeginDate, selectedEndDate ) )
    {
        return DateUtil.getHourOf( selectedBeginDate );
    }

    return ComplianceConstants.DEFAULT_COMPLIANCE_CASE_MIN_END_HOUR;
}

This basically only says if a begin date has been set and it the begin and end dates are currently the same, restrict the selectable end hour (minHour of end-date) to the begin hour.

Operations:

Set the begin datetime to 2013-04-20 12:34 (legit)
Set the end   datetime to 2013-04-22 00:00 (legit)

Now the time for end date sits on 00:00 and selecting a calendar date 2013-04-20 should be allowed as long as the end time is somehow adjusted to at least 12:35.

The p:calendar component however cannot know this and now

sets the end datetime to 2013-04-20 00:00 (legit, but false)

...

The problem now is that when the user presses a certain new end date in the calendar, the mindate/maxdate attributes cannot restrict the user to hit the the same as the begin date. If the end date time now happens to be before the same begin date's time there's nothing we can do about it (which is wrong).

The followup problem now is that the user is able to close the calendar and just press the submit button to insert false data into the DB. Of course, a validator could/should be run, but we have to somehow achieve this without a validator.

What we were trying next was to patch the setSelectedBeginDate( Date selectedBeginDate ) and setSelectedEndDate( Date selectedEndDate ) methods to adjust the set java.util.Date time portions if the dates were on the same day. Something like this:

public void adjustSelectedEndDate()
{
    if ( this.selectedEndDate != null )
    {
        this.log.infov( "adjustSelectedEndDate: b-hour = {0}, e-hour = {1}", DateUtil.getHourOf( this.selectedBeginDate ), DateUtil.getHourOf( this.selectedEndDate ) );

        if ( DateUtil.isSameDay( this.selectedBeginDate, this.selectedEndDate ) &&
            ( DateUtil.getHourOf( this.selectedEndDate ) < DateUtil.getHourOf( this.selectedBeginDate ) ) ||
              DateUtil.getHourOf( this.selectedEndDate ) == DateUtil.getHourOf( this.selectedBeginDate ) && DateUtil.getMinuteOf( this.selectedEndDate ) <= DateUtil.getMinuteOf( this.selectedBeginDate ) )
        {
            this.log.info( "Adjusting selected end date!" );

            this.selectedEndDate = DateUtil.addOneMinuteTo( DateUtil.copyTime( this.selectedBeginDate, this.selectedEndDate ) );
        }
    }
}

This required us to add @this to the update attribute of each p:calendar so that the respective getters (getSelectedBeginDate() and getSelectedEndDate + the min/max limiters) will be called during update.

Placing an @this on the update however confuses the p:calendar components, making the time sliders only slidable once. Subsequent slider events are simply ignored, behaving broken.

Q's

  • How do you generally approach solving this?
  • Is using p:remoteCommand the way to achieve what we want?

Optional Q:

  • Why hasn't the PrimeFaces p:calendar been implemented to provide a single minDateTime and maxDateTime, which could potentially solve the problems at hand?

I bet this scenario I described has already been solved before. I'd very much appreciate if you could describe the approach you managed to solve this (or even share a partly solution).


Source: (StackOverflow)

RichFaces Vs PrimeFaces [closed]

I am using JSF 2.0 and I am looking for a copmponent library with minimal load in terms of performance. Which one is better to use if I have choice between RichFaces and PrimeFaces? What are the advantages and disadvantages of both?


Source: (StackOverflow)

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null

I'm trying to upload a file using PrimeFaces, but the fileUploadListener method isn't being invoked after the upload finishes.

Here is the view:

<h:form>
    <p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
        mode="advanced" 
        update="messages"
        sizeLimit="100000" 
        allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>

    <p:growl id="messages" showDetail="true"/>
</h:form>

And the bean:

@ManagedBean
@RequestScoped
public class FileUploadController {

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

}

I've placed a breakpoint on the method, but it's never called. When using mode="simple" and ajax="false", it is been invoked, but I want it to work in the advanced mode. I'm using Netbeans and Glassfish 3.1.


Source: (StackOverflow)

Understanding process and update attributes of PrimeFaces

What exactly are process and update in PrimeFaces UICommand components? Which works at the time of validation? What does update attribute do rather than updating value to component from back end? Do process attribute bind value to model? What exactly do @this, @parent, @all and @form in both attributes?

The example below is working fine, but I am a little confused in basic concepts.

<p:commandButton process="@parent"
                 update="@form"
                 action="#{bean.submit}" 
                 value="Submit" />

Source: (StackOverflow)

Keep p:dialog open when a validation error occurs after submit

Minimal example dialog:

<p:dialog header="Test Dialog"  
          widgetVar="testDialog"> 
  <h:form> 
    <p:inputText value="#{mbean.someValue}"/> 

    <p:commandButton value="Save" 
                     onsuccess="testDialog.hide()" 
                     actionListener="#{mbean.saveMethod}"/> 
  </h:form>       
</p:dialog> 

What I want to be able to do is have the mbean.saveMethod somehow prevent the dialog from closing if there was some problem and only output a message through growl. This is a case where a validator won't help because there's no way to tell if someValue is valid until a save is submitted to a back end server. Currently I do this using the visible attribute and point it to a boolean field in mbean. That works but it makes the user interface slower because popping up or down the dialog requires hitting the server.


Source: (StackOverflow)

Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request

I find this article to be useful for non-ajax request How to handle session expiration and ViewExpiredException in JSF 2? but I can't make use of this when I am submitting using an AJAX call.

Suppose in a primefaces dialog, I am making a post request using AJAX and session has already timed out. I see my page getting stuck.

How to fix this kind of scenario such that when I post using AJAX, I could redirect him to my view expired page and then forward him to the login page similar to the solution in the link above?

JSF2/Primefaces/Glassfish


Source: (StackOverflow)

Defer loading and parsing of PrimeFaces JavaScript files

While analyzing the performance of a JSF 2.1 + PrimeFaces 4.0 webapp with Google PageSpeed, it recommends among others to defer parsing of JavaScript files. On a test page with a <p:layout> and a form with <p:watermark> and <p:fileUpload> which looks like follows ...

<p:layout>
    <p:layoutUnit position="west" size="100">Test</p:layoutUnit>
    <p:layoutUnit position="center">
        <h:form enctype="multipart/form-data">
            <p:inputText id="input" />
            <p:watermark for="input" value="watermark" />
            <p:focus for="input" />
            <p:fileUpload/>
            <p:commandButton value="submit" />
        </h:form>
    </p:layoutUnit>
</p:layout>

... it lists the following JavaScript files which could be deferred:

  • primefaces.js (219.5KiB)
  • jquery-plugins.js (191.8KiB)
  • jquery.js (95.3KiB)
  • layout.js (76.4KiB)
  • fileupload.js (23.8KiB)
  • watermark.js (4.7KiB)

It links to this Google Developers article wherein deferred loading is explained as well as how to achieve it. You basically need to dynamically create the desired <script> during the onload event of the window. At its simplest form whereby old and buggy browsers are completely ignored, it looks like this:

<script>
    window.addEventListener("load", function() {
        var script = document.createElement("script");
        script.src = "filename.js";
        document.head.appendChild(script);
    }, false);
</script>

Okay, this is doable if you have control over those scripts, but the listed scripts are all forcibly auto-included by JSF. Also, PrimeFaces renders a bunch of inline scripts to HTML output which are directly calling $(xxx) from jquery.js and PrimeFaces.xxx() from primefaces.js. This would mean that it would not easily be possible to really defer them to onload event as you would only end up with errors like $ is undefined and PrimeFaces is undefined.

But, it should be technically possible. Given that only jQuery doesn't need to be deferred as many of the site's custom scripts also rely on it, how could I block JSF from forcibly auto-including the PrimeFaces scripts so that I can defer them, and how could I deal with those inline PrimeFaces.xxx() calls?


Source: (StackOverflow)

Hide pagination buttons in table header of p:dataTable

I'm using <p:dataTable> of PrimeFaces 3.3.1 with pagination. The pagination buttons appear in both the table header and footer. I would like to hide the pagination buttons in the table header and keep the ones in the table footer. How can I achieve this?


Source: (StackOverflow)

h:outputtext is not breaking lines in \n

I got a <p:inputText> to insert a text into my database(Oracle)

But when i want to show the text using a <h:outputtext>, it doesn't recognize the return key \n

Code to input:

<p:inputTextarea id="txtInfoextra" value="#{empresaController.selected.infoExtra}" requiredMessage="#{i18n['default.required']}" rows="10" cols="25" maxlength="1000" autoResize="false" />

Code to output:

<h:outputText value="#{tecnologiaEmpresaController.selected.empresa.infoExtra}"/>

getInfoExtra comes with the value(debugging):

Text1\r\nText2\r\nText3

But it is showing in my page:

Text1 Text2 Text3 

Why the tag h:outputtext doesn't break lines in \n?

What should i do? replace \n to <br /> ?

Thank you !


Source: (StackOverflow)

JSF(Primefaces) ajax update of several elements by ID's

One more question concerning JSF.Particularly, Primefaces.
Have following problem with ajax update of elements by id's at same time. If elements on page goes one by one ,that ajax update performs ok:

<ui:repeat value="#{showProducts.inCart}" var="cart">
 <td><p:spinner min="0" value="#{cart.count}" immediate="true">
 <p:ajax process="@this" update="count,subTotal"/></p:spinner></td>         
 <td><h:outputText value="#{cart.totalPrice}" id="count"/></td>
 <h:outputText value="#{showProducts.subTotal}" id="subTotal"/>      
</ui:repeat>

Here element with id "count" goes first,then element with id "subtotal" goes second. In case,elements on page are not strictly one by one,that second element with "subtotal" id is not updated:

    <ui:repeat value="#{showProducts.inCart}" var="cart">
      <td><p:spinner min="0" value="#{cart.count}" immediate="true">
<p:ajax process="@this" update="count,subTotal"/></p:spinner></td>         
      <td><h:outputText value="#{cart.totalPrice}" id="count"/></td>
      <td><h:outputText value="#{cart.place}" /></td>
    </ui:repeat>
    <h:outputText value="#{showProducts.subTotal}" id="subTotal"/> 

Is it normal behaviour or I miss some parameters?


Source: (StackOverflow)

Difference between ".class" and ".class, .class .class"?

The following excerpt from the PrimeFaces documentation makes it seem as there is a difference between the two selectors described in the title:

.ui-widget, .ui-widget .ui-widget {
     font-size: 90% !important;
}

Can someone explain the significance of the second selector (".ui-widget .ui-widget") to me? I understand that it matches elements of class "ui-widget" that are themselves children of other elements of the same class, but wouldn't those already be selected by the first selector?


Source: (StackOverflow)

PrimeFaces commandButton doesn't navigate or update

I'am using Primefaces to make my app a little bit more beautiful. I noticed that p:commandButton and h:commandButton don't work the same way.

The p:commandButton calls the method and nothing else hapens. The h:commandButton calls the method and returns a navigation.

I have got trouble with redirecting after pressing the login button when using p:commandButton. How to deal with that?


I do have an update parameter:

<p:commandButton value="Login" action="#{login.login}" type="submit" update="msgs" />

Source: (StackOverflow)

Find component by ID in JSF

I want to find some UIComponent from managed bean by the id that I have provided.

I have written the following code:

private UIComponent getUIComponent(String id) {  
      return FacesContext.getCurrentInstance().getViewRoot().findComponent(id) ;  
}

I have defined a p:inputTextarea as:

<p:inputTextarea id="activityDescription" value="#{adminController.activityDTO.activityDescription}" required="true" maxlength="120"
    autoResize="true" counter="counter" counterTemplate="{0} characters remaining." cols="80" rows="2" />

Now if a call to the method as getUIComponent("activityDescription") it is returning null, but if I call it as getUIComponent("adminTabView:activityForm:activityDescription") then I can get the org.primefaces.component.inputtextarea.InputTextarea instance.

Is there any way to get the component with only the id i.e., "activityDescription" not the absolute id i.e., "adminTabView:activityForm:activityDescription"?


Source: (StackOverflow)