Search code examples
primefacesjsf-2commandlink

How to set p:commandLink tag "target" value after validating form value?


In my project I am having a command link in which "target" attribute value is set to "_blank". So if validation error comes it will open a new window and show the error message.

But the requirement is if validation is correct it should target to new window otherwise it will remain in the same page and show the error message.

existing code :

    <p:commandLink value="View"
     styleClass="view_link" 
     ajax="false"
     action="#{bean.someMethod('preview')}" 
     target ="_blank"  />

My soln:

    <p:commandLink value="View"
    styleClass="view_link" 
    ajax="false" 
    action="#{bean.someMethod('preview')}"
    target="#{bean.target}">
    <p:ajax listener="#{bean.handelAjaxBehavoiurEvent}"/>
    </p:commandLink>

In the listner method I am validating the form and setting target value for p:commandlink. But it is not working.

Expected result : When I click on the link it should validate the form values. If values are correct then open a new tab in the browser and preview the pdf file. Else show the error message on the existing page.

It is why because while checking on the link itself it will open the new. I want to set the value of target attribute after form validation.


Solution

  • This is, how I do such things:

    I have a xhtml-page to view any PDF (i.e. mypdfviewer.xhtml). The bean sets up some return args like validationOk, pdfname, viewoptions etc and returns these args via addCallbackParam(). In oncomplete I look for these values and, if ok, open the new tab.

    Dialog:

    <p:commandLink ajax="true" value="View" action="#{bean.someMethod('preview')}" oncomplete="return myPdfView(args)"/>
    

    Bean:

    public void someMethod(String what) {
      ...
      RequestContext.getCurrentInstance().addCallbackParam("validationOk", true);      
      RequestContext.getCurrentInstance().addCallbackParam("pdfFile", myfile);
    

    JavaScript:

    function myPdfView(args) {
      if(args && args.validationOk) {
        window.open("mypdfviewer.xhtml?file=" + args.pdfFile, '_blank');
      }
    }