Scroll p:messages into view when it is updated and (error) messages are present

前端 未结 4 1253
暖寄归人
暖寄归人 2021-01-05 18:58

I am working with PrimeFaces messages, I want my whole page to scroll to top when p:messages is rendered.

4条回答
  •  花落未央
    2021-01-05 19:44

    There are valid answers already that show how to scroll to the p:messages component, but they all require you to execute code in a backing bean. This requires you to do / call the same in each action. None show how to scroll to the messages component when it is rendered (updated).

    You can implement a phase listener and check messages are present and if the messages component's clientId is present in the PartialViewContext renderIds:

    These client identifiers are used to identify components that will be processed during the render phase of the request processing lifecycle.

    Your listener can look something like this:

    public class MessagesUpdateListener implements PhaseListener {
    
      private final String MESSAGES_ID = "yourMessagesClientId";
    
      @Override
      public void afterPhase(PhaseEvent event) {
        // Empty
      }
    
      @Override
      public void beforePhase(PhaseEvent event) {
        FacesContext fc = FacesContext.getCurrentInstance();
        if (!fc.getMessageList().isEmpty() &&
            fc.getPartialViewContext().getRenderIds().contains(MESSAGES_ID)) {
          RequestContext.getCurrentInstance().scrollTo(MESSAGES_ID);
        }
      }
    
      @Override
      public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
      }
    
    }
    

    Make sure to register it in your faces-config.xml:

    
      your.MessagesUpdateListener
    
    

    Tested with XHTML:

    
    
      
      
    
      this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page
    this
    is
    a
    long
    page

    To check for global messages, use:

    fc.getMessageList(null).isEmpty()
    

    See also:

    • Add global message when field validation fails

提交回复
热议问题