Command executes multiple times for menuitems added dynamically to Primefaces SplitButton

165 Views Asked by At

So added primefaces p:splitButton component inside a p:dataView component:

<p:dataView var="product" value="bean.products">
   ...
   //for each item in dataView, I add this split button with a couple of menuitem options
   <p:splitButton value="Select Option" icon="pi pi-list" appendTo="@this" model="#{bean.model}" />
   ...
</p:dataView>

Building the model:

...
DefaultMenuModel menuModel = new DefaultMenuModel();
DefaultMenuItem menuitem = DefaultMenuItem.builder().value("opt1").command("bean.foo1(product)").build();
menumodel.getElements().add(menuitem);
DefaultMenuItem menuitem = DefaultMenuItem.builder().value("opt2").command("bean.foo2(product)").build();
menumodel.getElements().add(menuitem);

The p:dataView ends up looking like this

---

Product 1
[Select Option^]
 | Opt 1 |
 | Opt 2 |

---

Product 2
[Select Option^]
 | Opt 1 |
 | Opt 2 |

---
...
---

Product 12
[Select Option^]
 | Opt 1 |
 | Opt 2 |

---

These are the methods called by the menuitems:

public void foo1() {
  System.out.println("first menu item was clicked inside "+product.getName());
}

public void foo2() {
  System.out.println("second menu item was clicked inside "+product.getName());
}

So now, when I run the app, this page would display 12 products per page, each with its p:splitButton with the two subitems.

When I click the first menuitem on the first product, it prints a single line as follows:

first menu item was clicked inside Product 1

When I click a menuitem on any subsequent product, it prints a line for each of the prior products, including the clicked one.

So if I click the first submenu item for the 7th product, it prints out:

first menu item was clicked inside Product 1
first menu item was clicked inside Product 2
first menu item was clicked inside Product 3
first menu item was clicked inside Product 4
first menu item was clicked inside Product 5
first menu item was clicked inside Product 6
first menu item was clicked inside Product 7

and so forth...

Does anyone know how to avoid this?

0

There are 0 best solutions below