4

h:message を「span」要素ではなく「p」html 要素としてレンダリングするカスタム メッセージ レンダラーを作成したいと考えています。これは、次のメッセージ タグに関係します。

<h:message id="firstNameErrorMsg" for="firstname" class="error-msg"  />

下にコードを書きましたが、それは空の 'p' 要素をレンダリングするだけです。元のコンポーネントからすべての属性とテキストをコピーして、ライターに書き込む必要があると思います。しかし、どこですべてを見つけることができるのかわかりません。タグを置き換えるだけでも大変な作業のようです。

h:message タグを「p」要素としてレンダリングするより良い方法はありますか?

コード:

@FacesRenderer(componentFamily = "javax.faces.Message", rendererType = "javax.faces.Message")
public class FoutmeldingRenderer extends Renderer {

    @Override
    public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException {

        ResponseWriter writer = context.getResponseWriter();
        writer.startElement("p", component);
        writer.endElement("p");

    }
}
4

1 に答える 1

7

It isn't exactly "a lot of work". It's basically a matter of extending from the standard JSF messages renderer, copypasting its encodeEnd() method consisting about 200 lines then editing only 2 lines to replace "span" by "p". It's doable in less than a minute.

But yes, I agree that this is a plain ugly approach.

You can consider the following alternatives which are not necessarily more easy, but at least more clean:

  1. First of all, what's the semantic value of using a <p> instead of a <span> in this specific case? To be honest, I'm not seeing any semantic value for this. So, I suggest to just keep it a <span>. If the sole functional requirement is to let it appear like a <p>, then just throw in some CSS. E.g.

    .error-msg {
        display: block;
        margin: 1em 0;
    }
    

  2. You can obtain all messages for a particular client ID directly in EL as follows, assuming that the parent form has the ID formId:

    #{facesContext.getMessageList('formId:firstName')}
    

    So, to print the summary and detail of the first message, just do:

    <c:set var="message" value="#{facesContext.getMessageList('formId:firstName')[0]}" />
    <p title="#{message.detail}">#{message.summary}</p>
    

    You can always hide it away into a custom tag file like so:

    <my:message id="firstNameErrorMsg" for="firstname" class="error-msg" />
    

  3. Use OmniFaces <o:messages>. When the var attribute is specified, then you can use it like an <ui:repeat>.

    <o:messages for="firstNameErrorMsg" var="message">
        <p title="#{message.detail}">#{message.summary}</p>
    </o:messages>
    
于 2013-11-01T19:40:26.700 に答える