jsf,jsf-2,primefaces,jsf-2.2 , Panel created dynamically is shown on XHTML but missing on getViewRoot


Panel created dynamically is shown on XHTML but missing on getViewRoot

Question:

Tag: jsf,jsf-2,primefaces,jsf-2.2

Panel is created and added to xhtml right but when I get it using findComponent("-formBotones-wizardEventContainer").getChildren() the result is null because its container got 1 children (id=tempTextIdLayer) when really html source show several children.

I've tried a solution with visitTree() but vars target and panel are the same, wizarEventContainer, and the got only 1 children (input hidden)

HtmlPanelGroup panel=(HtmlPanelGroup)FacesContextWrapper.getCurrentInstance().getViewRoot().findComponent("formBotones-wizardEventContainer");

    panel.visitTree(VisitContext.createVisitContext(FacesContext.getCurrentInstance()),new VisitCallback() {

        @Override
        public VisitResult visit(VisitContext context, UIComponent target) {
             if (target instanceof HtmlPanelGroup) {
                 HtmlPanelGroup layer = (HtmlPanelGroup) target;
                    System.out.println("id: " + layer.getId()); //wizardEventContainer                  // Collect them in an arraylist orso.
                }

                return VisitResult.ACCEPT;
        }
    });

Main xhtml code

<h:form id="formBotones" prependId="true">
        <h:panelGroup layout="block" id="wizardEventContainer" styleClass="wizardEventContainer">
            <h:inputHidden id="tempTextIdLayer" value="#{eventProvider.tempTextIdLayer}" />
        </h:panelGroup>
    </h:form>

HTML when panel is added

<form id="formBotones">
    <input type="hidden" value="formBotones" name="formBotones">

    <div class="wizardEventContainer" id="formBotones-wizardEventContainer">
        <div data-widget="widget_formBotones_text_11_0" id="formBotones-text_11_0">

            <div class="ui-panel-content ui-widget-content" id="formBotones-text_11_0_content">
                <span id="formBotones-editor_text_11_0">Dynamic text</span>
            </div>

            <div class="ui-resizable-handle ui-resizable-e" style="z-index: 90;"></div>
            <div class="ui-resizable-handle ui-resizable-s" style="z-index: 90;"></div>
            <div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90;"></div>

        </div>

        <input type="hidden" value="text_11_0" name="formBotones-tempTextIdLayer" id="formBotones-tempTextIdLayer">
    </div>

    <input type="hidden" value="e5s4" id="javax.faces.ViewState" name="javax.faces.ViewState">
</form>

Create layers code

Here, it's a method which is setted to button's actionListener. It create a resizable and draggable panel with a span where I'll write dynamic text through javaScript.

    public void createTextLayer() throws IOException{
    logger.entry("EventProvider.createTextLayer()");

    Application app=FacesContextWrapper.getCurrentInstance().getApplication();
    UIComponent parent=FacesContextWrapper.getCurrentInstance().getViewRoot().findComponent("formBotones-wizardEventContainer");
    CommandButton textBtn=(CommandButton)FacesContextWrapper.getCurrentInstance().getViewRoot().findComponent("formControl-textLayerBtn");

    String finalId=null;

    if(tempObjs!=null && tempObjs.size()>0 && tempObjs.containsValue("text")){
        finalId="text_" + space.getIdSpace() + "_" + createFinalIndex("text");
    }
    else{
        finalId="text_" + space.getIdSpace() + "_" + spaceBo.getDao().countSectionPages(space.getIdSpace(),4);
    }


    if(parent!=null){


        HtmlPanelGroup panel=(HtmlPanelGroup)app.createComponent(HtmlPanelGroup.COMPONENT_TYPE);
            panel.setId(finalId);
            panel.setStyleClass(panel.getId());
            panel.setStyle("display:inline-block;min-width:100px;min-height:100px;background:red;overflow:hidden;");
            setTempTextIdLayer(finalId);


        HtmlOutputText text=(HtmlOutputText) app.createComponent(HtmlOutputText.COMPONENT_TYPE);
            text.setId("editor_" + panel.getId());

        panel.getChildren().add(text);


        Resizable resizable=(Resizable)app.createComponent(Resizable.COMPONENT_TYPE);

            resizable.setFor(panel.getId());
            resizable.setMaxWidth(new Integer(800));
            resizable.setMaxHeight(new Integer(600));
            resizable.setMinWidth(new Integer(50));
            resizable.setMinHeight(new Integer(50));
            resizable.setContainment(false);
            resizable.setFor(panel.getId());

            panel.getChildren().add(resizable);         


        Draggable drag=(Draggable)app.createComponent(Draggable.COMPONENT_TYPE);

            drag.setFor(panel.getId());
            drag.setOpacity(new Double(0.6));
            drag.setContainment(new String("parent"));
            drag.setSnap(true);
            drag.setSnapMode(new String("outer"));
            drag.setSnapTolerance(new Integer(5));
            drag.setFor(panel.getId());

            panel.getChildren().add(drag);

        tempObjs.put(panel,"text");
    }

    updateViewRoot();

    //Disabling text button
    textBtn.setDisabled(true);
}

Add layer to container code

Here I get the container, wizardEventContainer, and I add every panel which are saved on tempObjs var.

public void updateViewRoot(){
    logger.entry("EventProvider.updateViewRoot()");

    UIComponent parent=FacesContextWrapper.getCurrentInstance().getViewRoot().findComponent("formBotones-wizardEventContainer");

    if(parent!=null){
        for (Entry<UIComponent, String> entry : tempObjs.entrySet()) {
            parent.getChildren().add(entry.getKey());
        }
    }
}

Answer:

As getViewRoot() only return elements which are written on xhtml file I've decided to save dynamic components in a map and when I place this dragabble component in the right site the I pass css style and other properties through managed bean properties, so every time a new panel is added on xhtml I create a new dynamic component with new properties setted and I replace for old dynamic component saved in the map.

It's a no elegant way but works fine at the moment for me.

    public void saveTextLayer(){
    logger.entry("EventProvider.saveTextLayer()");

    List<UIComponent> list=null;

    if(tempObjs.containsValue("text"))
         list=getKeysByValue(tempObjs,"text");

    for (UIComponent c:list){
        if (c instanceof HtmlPanelGroup){
            HtmlPanelGroup panel=(HtmlPanelGroup)c;

            if(panel.getId().equals(getTempTextIdLayer())){
                panel.setStyle(getTempCSS());
                if(panel.getChildren().get(0) instanceof HtmlOutputText){
                    ((HtmlOutputText)panel.getChildren().get(0)).setValue(getTempHTML());
                }

                //Adding delete layer
                Application app=FacesContextWrapper.getCurrentInstance().getApplication();

                HtmlPanelGroup deleteLayer=(HtmlPanelGroup)app.createComponent(HtmlPanelGroup.COMPONENT_TYPE);
                    deleteLayer.setId("delete_" + panel.getId());
                    deleteLayer.setStyle("display:inline-block;width:5px;height:5px;background:white;");
                    deleteLayer.setOnclick("deleteLayer($(this));");
                panel.getChildren().add(0,deleteLayer);

                //Replacing UIComponent
                tempObjs.remove(c);
                tempObjs.put(panel, "text");

                updateViewRoot();

                //Deleting temp vars
                setTempCSS("");
                setTempTextIdLayer("");
                setTempHTML("");
            }
        }
    }

Related:


Why are fields reset after ajax update with Primefaces


ajax,jsf-2,primefaces
On a form I have some personal information (name, address etc.) and a changeListener which updates the salutation and letter salutation according to the gender and last name. If the underlying entity was already stored in the database it works fine. If I'm entering data for a new (not saved)...

Eclipse + Wildfly + Maven EAR project, is it possible to have files update without redeploy?


eclipse,jsf,jsf-2.2,wildfly-8
I'm working on my first JavaEE/JSF project. It's currently set up with maven so that several jars and a war are deployed inside an EAR container. I spent a lot of time trying to get some kind of hot/autoredeploy type setup going a few weeks ago but gave up and...

Render hidden elements using JSF and AJAX


ajax,jsf,jsf-2.2
I've been facing some problems using JSF with AJAX to render a table without reloading the whole page every time I submit a form. When I first run the server, my database is empty, so the page is supposed to show only a form to add books. When user submits...

Primefaces: Dialog with inputTextarea not updating controller's variable


jsf,jsf-2,primefaces
I have this Dialog: <p:dialog header="Ingrese Comentario" widgetVar="dlg1" appendTo="@(body)" modal="true" position="top" hideEffect="fold" showEffect="fold" closable="true" draggable="true" > <h:form id="d_ingresarComentario"> <h:panelGrid columns="2"> <p:inputTextarea value="#{tareaController.comentarioNuevo.comentario}" rows="7" cols="60" placeholder="Ingrese su comentario aquí" counter="display1" maxlength="200" counterTemplate="{0} Caracteres faltantes." > </p:inputTextarea> <br/>...

how stick out a menu when clicking on a menu [on hold]


css,jsf,primefaces
I have a type of menu created in JSF. <p:menubar styleClass="menuPrincipal" id="menuBar" > <p:menuitem value="Inicio" url="/Inicio.xhtml" style="text-decoration:none" icon="ui-icon-home" id="inicio" /> <p:menuitem value="Agregar Excepciones" id="agregarExcepcion" url="/ExcepcionNuevo.xhtml" style="text-decoration:none" rendered='#{excepcionPendienteView.usuarioActual.tipoSolicitante eq "Administrador"}' /> </p:menubar> I want that when you click on a menu, highlight the option me where I am working. if I...

Retrieve the id of an Entity object as soon as the entity was instantiated?


jsf,jpa
Is there a way in JPA to retrieve the id of an Entity object as soon as the entity was instantiated? e.g Person person = new Person(); Currently i am using in my entity class the following strategy: @GeneratedValue(strategy = GenerationType.IDENTITY) If not is there a "Dummy Id" strategy for...

af:convertNumber element removes zero in the end of the value


jsf,numbers,converter,oracle-adf
My code: <af:inputText id="it1" label="Test"> <af:convertNumber groupingUsed="true" type="number" messageDetailConvertNumber="#,###,##" maxFractionDigits="2"/> </af:inputText> When I type 100,51 -- everything is fine, but if I would type 100,50, then '0' will be removed and entered value will be 100,5. How can I leave this '0' in the end? I need <af:convertNumber> element for...

Portlet IPC after recieved Event


jsf,events,event-handling,ipc,portlet
I have a Navigation portlet which schows all Students, when a Student gets clicked im sending a event with the id of the clicked student to other portlets. Sending and receiving the event is not the problem, that works fine. What i don't get, is how to proceed with the...

h:selectmanyListbox make “choose” option unselectable when at least one option is selected


jsf,jsf-2,selectmanylistbox
Is it possible to have in <h:selectManyListbox> a default option like "--choose--" which can be selected when no option is selected. When the some value is chosen, then it must be unselectable. <h:selectManyListbox value="#{bean.value}" class="form-control"> <f:selectItems value="#{bean.dropdownValues}" var="value" itemLabel="#{value}" itemValue="#{value}"/> </h:selectManyListbox> ...

Refresh selection model of p:datatable on row deselection


jsf,primefaces,datatable,selection
I have a problem with the selection model of a Primefaces 5.0 datatable. This selection model does not process deselection properly: Selection of rows adds these roles as expected to the list of selected rows. But a deselection has no influence on this list; deselected rows remains in it. Only...

Is there a way to get the Base URL from an Application-scoped bean in JSF?


jsf,servlets,jsf-2
In my JSF Facelets pages I know I can just use #{request.requestURL} To get the full URL to build exportable links and the like. However I have an @ApplicationScoped bean where I need the base URL (i.e. "http://dnsname/app") for the purposes of reports and other data. Is there a standard...

How to click on a p:commandButton using javascript [duplicate]


javascript,jsf,callback,commandbutton
This question already has an answer here: How to select JSF components using jQuery? 2 answers There are many tag in my JSF page.I want to click a p:commandButton using javascript in one of the forms. But it doesn't work. When I debug it use chrome ,it prompt The...

javax.servlet.ServletException the request doesn't contain a multipart/form-data or multipart/mixed stream


ajax,jsf,file-upload,jsf-2.2,mojarra
I've the below form which uploads a file via <h:inputFile> and <f:ajax>. <h:form enctype="multipart/form-data"> <h:inputFile id="file" value="#{bean.file}" /> <h:commandButton value="Upload" action="#{bean.upload}"> <f:ajax execute="file" render="file" /> </h:commandButton> </h:form> When I submit it, I get a JavaScript alert with the below error information: serverError: class javax.servlet.ServletException the request doesn't contain a multipart/form-data...

Distinguish view from normal view in ViewHandler#createView()


jsf,custom-error-pages,viewhandler
I have defined error page in my web.xml for error 404 in this way: <error-page> <error-code>404</error-code> <location>/common/messages/pageNotFoundError.jsf</location> </error-page> Handling invalid page url works as intended - user is redirected to pageNotFoundError page. I have also defined custom view handler in faces-config.xml. The view handler overrides method createView(FacesContext context, String viewId)....

CommandButton execution while rendering


jsf,primefaces
Question: How can I prevent the execution of a while the website is rendering? Thats where my Button sits: <p:dialog widgetVar="newComment" height="200" width="500"> <h:form> <h:panelGrid> <h:outputText value="#{commentDialog.username}" /> <h:inputTextarea id="in_text" value="#{commentDialog.text}" /> <p:message for="in_text" /> </h:panelGrid> <p:commandButton validateClient="true" value="Abschicken" ajax="true" actionListener="#{popupRequestView.update}"...

Creating command links dynamically from a managed bean


jsf
I have a need to create command links dynamically based on content coming from elsewhere. When a user clicks on a link it should call a method in a managed bean, and the method needs to know which link was clicked. I can create the command links using the following...

Putting inside a causes “weird” display


jsf-2,primefaces,panelgrid
I want to create dynamic forms with ajax update on event. Therefore dynamic-id is important. However, binding the id attribute to a bean value causes Empty Id exception. I saw one of the stackoverflow questions that suggests use html. So I used span. The xhtml code is as follows: <?xml...

Is there a JSF toggle component or a way to theme an h:selectBooleanCheckbox with images?


jsf,button,checkbox,toggle
I tried using a toggle like below. Although it works, it breaks when used inside of a composite component - changing the singleSelect value outside of the component never updates inside the component: <h:commandButton disabled="#{cc.attrs.singleSelect}" image="/resources/img/collapse-single.gif"> <f:ajax listener="#{cc.toggleSingleSelect}" render="#{cc.clientId}"/> </h:commandButton> <h:commandButton disabled="#{! cc.attrs.singleSelect}" image="/resources/img/expand-single.gif"> <f:ajax...

How to display PDF in JSF, with content from ServletResponse


jsf,pdf,jsf-2,richfaces
In my application, I use jsf & richfaces, I want to display a generated pdf in web browser , I have generated this PDF in serverside and it is available in ServletResponse, but I am unable to display it in my web page. I have tried this question but, it...

Refresh parent node from backing bean with primefaces tree


jsf,primefaces,tree
Currently I am working on a project that use primefaces 3.4.1 version which does not support drag and drop in tree component. So I am using a contextMenu instead of drag and drop. <p:tree id="treeHierarchy" value="#{hierarchyManagementBackingBean.root}" var="node" dynamic="true" selectionMode="single" cache="false" style="width:99%;" selection="#{hierarchyManagementBackingBean.selectedNode}"> <p:treeNode id="idtreenode"> <h:outputText value="#{node.name} (#{node.entityType})" /> </p:treeNode> </p:tree>...

How to generate a component multiple times in JSF?


google-maps,jsf-2,gmaps4jsf
I need to highlight the boundary of a country, for which I am using GMaps4JSF aimed at integrating Google maps with JSF. To draw polygon and polylines, the library provides polygonComponent polylineComponent components. I have loaded the data points from the fusion tables into our own DB. <m:map width="1000px" height="500px">...

Setting f:setPropertyActionListener value with a f:param value


jsf,jsf-2,param,setpropertyactionlistener
I'm trying to use the setPropertyActionListener tag to set a value in my backing bean. However, it doesn't work as I expected. Context: userService is an instance of my backing bean, which contains an int member, reqID. This, in turn, is the key to a map of objects that belong...

Manually added faces message doesn't appear in tab of accordion panel


jsf,message
I'm adding a faces message in an action method as below: FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Mail invalide", "Vérifier le mail"); FacesContext.getCurrentInstance().addMessage("connection:mail", message); I'm expecting it to show up at the below position in the tree: <h:body> <p:layout fullPage="true"> <p:layoutUnit position="center" > <p:accordionPanel multiple="true" activeIndex="0"> <p:tab title="Se connecter" > <h:form...

java.util.ServiceConfigurationError when running tests using arquillian+omnifaces


java,jsf,jboss-arquillian,omnifaces
I am getting the following error "java.util.ServiceConfigurationError: javax.servlet.ServletContainerInitializer: Provider org.omnifaces.ApplicationInitializer not found" when running Arquillian tests. I have put the most basic test case I could here: https://www.dropbox.com/s/kou5v8kqs5g4g4m/test.zip?dl=0...

set focus to next input element after jsf's change value listener


javascript,jsp,jsf
in one of our front-end screens we have the following layout as follows <h:outputLabel for="firstName" value="first name" /> <h:inputText styleClass="required" id="firstName" size="30" maxlength="30" value="#{ownershipStoreInfoController.form.ownerFirstName}" onchange="submit()" valueChangeListener="#{ownershipStoreInfoController.useOwnerInfo}"> <e:validateRegExpr pattern="([A-Z,a-z,0-9,%@()#&amp;,.;:_\$\/\-\{\}\[\]\'\\s*]{1,30})?" /> </h:inputText> <h:outputLabel for="lastName" value="last name"...

Use JSF, JPA, JTA, JAAS, CDI, Bean Validation with Tomcat? [closed]


jsf,tomcat,jpa,cdi,jta
Is it possible to use the following APIs with tomcat (as a lightweight server): JSF, JPA, JTA, JAAS, CDI, Bean Validation. ...

Render outcome of “action” attribute?


jsf,attributes,action,renderer
i want to completely rewrite a <h:commandButton> renderer. Now i'm stuck at rendering the "action" attribute of the button. Is there a possibility to render this attribute the same way it gets rendered by the standard renderer ? Is there a possibility to retrieve the generated script from somewhere ?...

JSF link to external site without showing username and password in the URL


jsf,post,single-sign-on,commandlink
I was able to do a SSO(Single sign on) on click of external link from the code below. SSO works but username/password is seen on url. https://example.org/index.php?userLogin=user1&userPassword=pass123 <h:outputLink styleClass="ui-menuitem-link ui-corner-all" value="https://example.org/index.php"> <h:outputText value="Ext Tool" /> <h:outputText styleClass="ui-icon ui-icon-suitcase" style="float:left" rendered="#{userBean.in}" /> <f:param name="userLogin" value="#{userBean.user.eUser}" /> <f:param...

Why can't I reference net.sf.jasperreports.engine.DefaultJasperReportsContext from JSF?


java,jsf,jasper-reports
I grabbed an old JSF (in Netbeans) project that I needed to update. I noticed that the libraries were missing, so I went and snagged the current version of JasperReports (.jar) and all the commons/other support .jars necessary. Ultimately, when I try to run the project it fails at the...

Double dispatching in jsf


jsf,jsf-2
Is it possible in Mojarra-2.1. If I do dispatching to another view from the action method by clicking action buttons: <h:commandButton value="dispatch" action="#{myBean.action()}" /> The bean: @ManagedBean @RequestScoped public class MyBean{ public String action(){ //do some return "view"; } } my browser then recieve the content of the view view....

selectonemenu, when editable=false, cannot submit the form


jsf,primefaces
My form is working if editable is set to true but not when it's false. When false the submit action method is not even called. I need it to be false (not editable so I can store the correct value in db). This is the menu I added. <tr><td> <h:outputLabel...

Parameters from f:param not submitted with AJAX request when form enctype is multipart/form-data


ajax,jsf,jsf-2,jsf-2.2,wildfly
I'm running Wildfly 8.2 and I'm using the JSF version bundled with it, 2.2.8-jbossorg-1. I have the following facelet: <h:form enctype="multipart/form-data"> <h:commandButton value="Submit"> <f:param name="myparam" value="true"/> <f:ajax execute="@this" render="@this"/> </h:commandButton> </h:form> When I press the submit button, several parameters are submitted, but not myparam. If I remove enctype="multipart/form-data" from the...

JSF Composite Component with conditional popup panel


jsf,richfaces,el,composite-component
I'm trying to render a composite component that shows a popup panel based on the outcome of a backing bean method. So far no success. Would appreciate some help. GlassFish 4.1 Mojarra 2.2 RichFaces 4.5.4 Composite Component (conditionalActionLink.xhtml): <ui:component xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich" xmlns:ui="http://java.sun.com/jsf/facelets"...

a4j:support - Value retrieved from h:selectOneMenu is always NULL


ajax,jsf,richfaces,ajax4jsf
There's a datatable with a h:selectOneMenu in each row. I want to be able to retrieve the value selected in the selectOneMenu in the bean. I'm using richfaces a4j:support tag to make AJAX calls to the backing bean. You can see the code below: DataTable header: <t:dataTable id="datatable" var="row" value="#{myBean.dataTableRows}">...

Can @ManagedBean and @XxxScope be placed in a base class?


jsf,jsf-2,subclass,managed-bean
I have two @ManagedBean (javax.faces.bean.ManagedBean), parent and child. The parent managed bean is not abstract because we have to give liberty to the developer to use the parent if enough or inherit it with a child that holds specifically funcionality. I have problems with the injections bean and the @PostConstruct...

Submit form without attached file


jsf,jsf-2.2
I want to create JSF form with attached file. But also to give a option form the users to submit the for without attach file. I don't want this to be mandatory. <h:form id="form" enctype="multipart/form-data"> <div class="string"> <label class="name"> <h:inputText id="name" value="#{contacts.name}" pt:placeholder="Name*:"/> </label> </div> <label class="message"> <h:inputTextarea value="#{contacts.comment}" pt:placeholder="Comment*:"/>...

Unable to load servlet listener class: com.sun.faces.config.ConfigureListener


maven,jsf,tomee
I'm using apache-tomee-jaxrs-1.7.1 and I'm trying to deploy with maven 3 getting this error: Unable to load servlet listener class: com.sun.faces.config.ConfigureListener: These are my dependencies in pom.xml: ... <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId>...

Execute a script on f:ajax “success” event only when validation has not failed


javascript,ajax,jsf-2,event-handling,composite-component
I have created a composite component that extends the command button and add some ajax functions (onBegin, onComplete and onSuccess), but I have some problems that I couldnt solve: When I click on the button and a validation error occur, in success event function is passed #{facesContext.validationFailed} = false instead...

Output and Command Link in one in JSF


jsf,hyperlink,action
Is there a possibility to use both outcome and action in the same command link? I tried <h:commandLink outcome="page?faces-redirect=true" value="Got to Page" action="#{Bean.setValue("...")}" /> but it ignores the outcome. I have a table with data like this: ID Name Other Things Link to Next Page So I want to give...

Dynamic rendering - unable to find component with clientId


jsf-2,primefaces
I am rendering a xhtml to a dialog whose components are added dynamically from server side using Dynamic example. Using PrimeFaces 5.1, JSF 2.1 Mojarra and tomcat 7. When i click the close button of the pop up a large number to of unable to find the component is being...

How can I load a resource bundle properties file within a composite component?


jsf,composite-component,resourcebundle,properties-file
My component library directory tree is setup as the following: resources mylib css mycomponent.css properties mycomponent.properties mycomponent.xhtml I'd like to load the properties file within mycomponent.xhtml to use for messages. What is the proper way of doing this? Is there an f:loadbundle type of solution?...

JSF facets not available in Eclipse


java,eclipse,jsf,facets
So I am watching a tutorial about how to configure JSF in eclipse. I understand that you click file -> new -> Dynamic Web Project. And then it gives you a few options. The Target Runtime will be (for me) Apache Tomcat version 8, and dynamic web module version will...