Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing SelectableDataModel

Tags:

jsf

primefaces

XHTML side:

<p:dataTable id="selectProductTable" var="product"  value="#{manageFormsView.productModel}" selection="#{manageFormsView.product}" >

bean side:

  private SelectableDataModel<Product>  productModel=new SelectableDataModel<Product>() {


                @Override  
                public Product getRowData(String rowKey) {  
                    //In a real app, a more efficient way like a query by rowKey should be implemented to deal with huge data  


                    for(Product product : productList) {  
                        if(product.getModel().equals(rowKey))  
                            return product;  
                    }  

                    return null;  
                }  

                @Override  
                public Object getRowKey(Product p) {  
                    return p.getModel();  
                }  
        };

i do not want to generate a new class which implements SDM, can not i do inline implementaton like above?

I am getting exception:

javax.faces.FacesException: DataModel must implement org.primefaces.model.SelectableDataModel when selection is enabled.
like image 650
merveotesi Avatar asked Nov 26 '25 11:11

merveotesi


1 Answers

The exception message is misleading. Implementing only the SelectableDataModel interface is not sufficient. You also need to extend an DataModel implementation such as ListDataModel. That can't be done in flavor of an anonymous class. You really need to create another class.

public class ProductDataModel extends ListDataModel<Product> implements SelectableDataModel<Product> {

    // ...

}

You can if necessary generify it if you have a common base entitiy (with getId() and so on), so that you don't need to create another one for every entity.

public class BaseEntityDataModel<E extends BaseEntity> extends ListDataModel<E> implements SelectableDataModel<E> {

    // ...

}

As a completely different alternative, you can also use rowKey attribtue of the <p:dataTable> and let it refer exactly the same value as SelectableDataModel#getRowKey(). This way you don't need the whole SelectableDataModel interface anymore.

<p:dataTable ... rowKey="#{product.model}">

See also:

  • PrimeFaces showcase example
like image 77
BalusC Avatar answered Nov 28 '25 01:11

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!