The context menu is displayed when the mouse is right-clicked. It replaces the native context menu in the browser and gives web applications a desktop-like feel and behavior. PrimeFaces' context menu provides an overlay with submenus and menu items.
In this recipe, we will develop a context menu with nested items and see how to attach it to any component. For example, we will attach the context menu to a panel
component.
The context menu is defined by the p:contextMenu
tag. We would like to define two submenus—one with menu items having URLs (they send GET
requests) and one with AJAX-ified menu items (they send POST
requests). AJAX-ified menu items perform the CRUD operations and update p:growl
. The context menu is attached to p:panel
. That means only a right-click on the panel
component displays the defined context menu. A click anywhere else displays the native web browser's context menu. This is shown in the following code:
<p:growl id="growl"/> <p:panel id="dummyPanel" header="Please click somewhere on panel to see a context menu"> <h:panelGroup layout="block" style="height:100px;"/> </p:panel> <p:contextMenu for="dummyPanel"> <p:submenu label="JavaScript Libraries"> <p:menuitem value="jQuery" url="http://jquery.com"/> <p:menuitem value="Yahoo UI" url="http://yuilibrary.com"/> <p:menuitem value="Prototype" url="http://prototypejs.org"/> </p:submenu> <p:separator/> <p:submenu label="Operations"> <p:menuitem value="Save" actionListener="#{contextMenuBean.save}" update="growl"/> <p:menuitem value="Update" actionListener="#{contextMenuBean.update}" update="growl"/> <p:menuitem value="Delete" actionListener="#{contextMenuBean.delete}" update="growl"/> </p:submenu> </p:contextMenu>
The following screenshot shows the result of the preceding code:
By default, contextMenu
without the defined for
attribute is attached to the whole page. That means a right-click somewhere on the page will display the menu. The for
attribute defines a component that contextMenu
is attached to. The value of for
specifies a search expression, which, in this case, is the ID of p:panel
.
Chapter 1, Getting Started with PrimeFaces, provides more details on search expressions.
Context menus can also be created programmatically and bound to p:contextMenu
by the model
attribute. Programmatic menus are discussed in the Creating programmatic menus recipe of this chapter.
Data iteration components have an exclusive integration with the context menu. Refer to the Integrating the context menu recipe to learn more about such integrations
This recipe is available in the demo web application on GitHub (https://github.com/ova2/primefaces-cookbook/tree/second-edition). Clone the project if you have not done it yet, explore the project structure, and build and deploy the WAR file on application servers compatible with Servlet 3.x, such as JBoss WildFly and Apache TomEE.
The showcase for the recipe is available at http://localhost:8080/pf-cookbook/views/chapter6/contextMenu.jsf
.