How to position a p:dialog in Prime Faces after it

2019-04-24 14:03发布

I have a Prime Faces p:dialog that has been resized while new components are inserted when opened ('show' state). However its position doesn't change and it's size is increasing from the down left corner until the page bottom.

I need to reposition it every time I render new components dynamically. Is there any JavaScript function I can call to its widget to reposition?

I'm using PrimeFaces 3.5 with Mojarra 2.1.13.

2条回答
The star\"
2楼-- · 2019-04-24 14:10

I had a similar situation with a TabView inside a dialog. The TabView content was dynamically loaded.

<p:dialog widgetVar="dialogWidgetVar">
    <p:tabView value="#{tabBean.tabs}" var="tabsVar"
            onTabShow="PF('dialogWidgetVar').initPosition();" dynamic="true">
        <p:tab id="Tab#{tabsVar.id}" title="#{tabsVar.name}">
            ...
        </p:tab>
    </p:tabView>
</p:dialog>

As you can see it will call the function initPosition() with every change of a Tab. This function will reposition your dialog. You can use this function in several cases.

  1. http://forum.primefaces.org/viewtopic.php?f=3&t=16893
查看更多
▲ chillily
3楼-- · 2019-04-24 14:28

This is a method that should work in your case :

Bean code :

@ManagedBean
@ViewScoped
public class Bean
{
    private boolean visible;

    public void setVisible(boolean visible)
    {
         this.visible = visible;
    }

    public boolean getVisible()
    {
        return this.visible;
    }

    public void onBeforeShowDialog(AjaxBehaviorEvent event)
    {
        visible = true;
    }

    public void onBeforeHideDialog(AjaxBehaviorEvent event)
    {
        visible = false;
    }
}

View code :

<h:commandButton value="Show dialog">
    <f:ajax listener="#{bean.onBeforeShowDialog}" render="dialog" />
</h:commandButton>

<p:dialog id="dialog" visible="#{bean.visible}">
    content

    <h:commandButton value="Hide dialog">
        <f:ajax listener="#{bean.onBeforeHideDialog}" render="dialog" />
    </h:commandButton>
</p:dialog>

A second method should also work is by JavaScript :

To add in <h:head /> :

<h:outputScript library="primefaces" name="jquery/jquery.js" />

<script>
    function centerAndShowDialog(dialog)
    {
        $(dialog).css("top",Math.max(0,(($(window).height() - $(dialog).outerHeight()) / 2) + $(window).scrollTop()) + "px");
        $(dialog).css("left",Math.max(0, (($(window).width() - $(dialog).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
        dialog.show();
    }
</script>

View code :

<p:commandButton id="basic" value="Show Dialog" onclick="centerAndShowDialog(dlg);" type="button" />

<p:dialog id="dialog" header="Dynamic Dialog" widgetVar="dlg" dynamic="true">
    Content
</p:dialog>

Note : Since I'm not using PrimeFaces, I've not tested this code so I hope it work well, but the idea is here!

查看更多
登录 后发表回答