问题描述
例如:
<p:selectOneMenu value="#{UserBean.country}" id="countryId">
<f:selectItem itemLabel="Japan" itemValue="Japan"/>
<f:selectItem itemLabel="Russia" itemValue="Russia"/>
<f:selectItem itemLabel="India" itemValue="India"/>
<p:ajax listener="#{UserBean.onChangeCountry}" process="@this"/>
</p:selectOneMenu>
像上面一样,我在其他jsf页面中还有许多其他的selectOneMenu,它们不是按排序的形式,我想要一个解决方案,其中在selectOneMenu标记和自定义标记之间将按排序顺序显示内容(或者也可以建议任何其他方式)我们可以实现这一目标)
Like above I have many other selectOneMenu in other jsf pages which is not in sorted form, I want a solution where in surrounding the selectOneMenu tag with the custom tag will display the contents in sorting order (or can suggest any other way also we can achieve this)
推荐答案
您可以为 p:selectOneMenu
组件创建自定义渲染器.创建一个新类,例如 my.custom.MySelectOneMenuRenderer
,然后扩展 SelectOneMenuRenderer
.在这种情况下,您要将 encodeInput
方法 @Override
设置为类似
You could create a custom renderer for the p:selectOneMenu
component. Create a new class, say my.custom.MySelectOneMenuRenderer
, and extend SelectOneMenuRenderer
. In this you want to @Override
the encodeInput
method to something like:
public class MySelectOneMenuRenderer extends SelectOneMenuRenderer {
@Override
protected void encodeInput(FacesContext context, SelectOneMenu menu, String clientId, List<SelectItem> selectItems, Object values, Object submittedValues, Converter converter) throws IOException {
// Sort the items
Collections.sort(selectItems, Comparator.comparing(SelectItem::getLabel));
// Delegate to super to continue rendering
super.encodeInput(context, menu, clientId, selectItems, values, submittedValues, converter);
}
}
我已经使用PrimeFaces 10进行了检查.如果您需要其他PrimeFaces版本的源代码,请检查 SelectOneMenuRenderer
源代码并选择相应的版本标记.请注意,您需要覆盖的方法在其他版本中可能会有所不同(不太可能,但可能).
I've checked this with PrimeFaces 10. If you need the source for a different PrimeFaces version, check the SelectOneMenuRenderer
source code and select the according version tag. Note that the method you need to override, might be different in other versions (not likely, but possible).
将自定义渲染器添加到 faces-config.xml
中的 render-kit
部分,例如:
Add your custom renderer to the render-kit
section in your faces-config.xml
like:
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.SelectOneMenuRenderer</renderer-type>
<renderer-class>my.custom.MySelectOneMenuRenderer</renderer-class>
</renderer>
</render-kit>
请注意,这将每次对任何 p:selectOneMenu
呈现器对选项进行排序,这会降低性能.
Please note that this will sort the options every time for any p:selectOneMenu
render, which comes with a performance penalty.
这篇关于如何在我的应用程序的每个p:selectOneMenu中对f:selectItems进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!