问题描述
XHTML方面:
<p:dataTable id="selectProductTable" var="product" value="#{manageFormsView.productModel}" selection="#{manageFormsView.product}" >
豆角:
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();
}
};
我不想生成一个实现SDM的新类,我不能像上面那样做内联实现吗?
i do not want to generate a new class which implements SDM, can not i do inline implementaton like above?
我遇到异常:
javax.faces.FacesException: DataModel must implement org.primefaces.model.SelectableDataModel when selection is enabled.
推荐答案
该异常消息具有误导性.仅实现SelectableDataModel
接口是不够的.您还需要扩展一个 DataModel
实现,例如ListDataModel
.不能做到匿名类.您确实需要创建另一个类.
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> {
// ...
}
如果您有一个共同的基本实体(带有getId()
等),则可以根据需要将其通用化,这样就不必为每个实体都创建另一个实体.
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> {
// ...
}
作为完全不同的替代方法,您还可以使用<p:dataTable>
的rowKey
属性,并使其引用与SelectableDataModel#getRowKey()
完全相同的值.这样,您就不再需要整个SelectableDataModel
接口.
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}">
另请参见:
- PrimeFaces展示示例
- PrimeFaces showcase example
See also:
这篇关于实现SelectableDataModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!