Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render JSF h:message with p element instead of span

I would like to create a custom message renderer to renders h:message as a 'p' html element instead of as a 'span' element. It concerns the following message tag:

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

I've written to code underneath, but that's only rendering an empty 'p' element. I suppose I have to copy all attributes and text from the original component and write it to the writer. However, I don't know where to find everything and it seems to be a lot of work for just a replacement of a tag.

Is there a better way to get an h:message tag rendered as a 'p' element?

Code:

@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");

    }
}
like image 660
Kees de Boer Avatar asked Mar 22 '23 19:03

Kees de Boer


1 Answers

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>
    
like image 133
BalusC Avatar answered Mar 24 '23 08:03

BalusC