How to parameterize requiredMessage attribute in composite component?

为君一笑 提交于 2019-11-30 23:15:58
BalusC

Unfortunately, the requiredMessage (and validatorMessage and converterMessage) attribues are not parameterizable by default. I think it would make little sense anyway as they are tied to a specific component in particular. A composite component does usually not contain a multiple of the same components. You would need to specify separate messages for every individual component.

It's in theory however possible to create a custom EL function which does the message formatting job. The method would look something like this:

public static String format(String message, Object argument1, Object argument2) {
    return MessageFormat.format(message, argument1, argument2);
}

which is to be used something like this:

requiredMessage="#{util:format(cc.resourceBundleMap.requiredMessage, cc.attrs.prefix, cc.attrs.label)}"

The only disadvantage is that you can't create EL functions which can take varargs. This is a limitation of the EL specification. So if you intend to be able to pass variable arguments, you'd need to create a separate EL function and a Java method for every possible amount of arguments needed.

As a completely different alternative, you could create a custom Validator and attach it to the particular input component. You can even put the validator method straight in the "backing component" which is associated with the composite component by <cc:interface componentType>. If you remove the required attribute, then this validator will immediately be invoked where you've the freedom to compose messages the way you want.

E.g.

<h:inputText id="foo" validator="#{cc.validateFoo}" requiredMessage="#{cc.resourceBundleMap.requiredMessage}" />

with

public void validateFoo(FacesContext context, UIComponent component, Object value) {
    if (value == null || value.toString().trim().isEmpty()) {
        String requiredMessage = (String) component.getAttributes().get("requiredMessage");
        String prefix = (String) getAttributes().get("prefix");
        String label = (String) getAttributes().get("label");
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
            MessageFormat.format(requiredMessage, prefix, label), null));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!