1 package org.appfuse.webapp.jsf; 2 3 import java.util.Iterator ; 4 import java.util.Map ; 5 6 import javax.faces.component.UIComponent; 7 import javax.faces.component.UIInput; 8 import javax.faces.context.FacesContext; 9 import javax.faces.context.ResponseWriter; 10 import javax.faces.render.Renderer; 11 12 import org.apache.commons.lang.StringUtils; 13 import org.apache.commons.logging.Log; 14 import org.apache.commons.logging.LogFactory; 15 16 23 public class LabelRenderer extends Renderer { 24 protected final Log log = LogFactory.getLog(LabelRenderer.class); 25 26 public boolean getRendersChildren() { 27 return false; 28 } 29 30 public void encodeBegin(FacesContext context, UIComponent component) 31 throws java.io.IOException { 32 ResponseWriter writer = context.getResponseWriter(); 33 34 Map attrs = component.getAttributes(); 35 String id = (String ) attrs.get("for"); 36 37 UIInput input = null; 38 39 if (!StringUtils.isEmpty(id)) { 40 input = (UIInput) component.findComponent(id); 41 } 42 43 writer.startElement("label", component); 44 45 String styleClass = (String ) component.getAttributes().get("styleClass"); 46 47 boolean hasErrors = hasMessages(context, input); 48 49 if (styleClass != null) { 50 if (hasErrors) styleClass += " error"; 51 writer.writeAttribute("class", styleClass, null); 52 } else if (hasErrors) { 53 writer.writeAttribute("class", "error", null); 54 } 55 56 String renderedId = 57 (input != null) ? input.getClientId(context) 58 : component.getClientId(context); 59 writer.writeAttribute("for", renderedId, null); 60 writer.write(attrs.get("value").toString()); 61 } 62 63 public void encodeEnd(FacesContext context, UIComponent component) 64 throws java.io.IOException { 65 ResponseWriter writer = context.getResponseWriter(); 66 67 Map attrs = component.getAttributes(); 68 String id = (String ) attrs.get("for"); 69 70 UIInput input = null; 71 72 if (!StringUtils.isEmpty(id)) { 73 input = (UIInput) component.findComponent(id); 74 } 75 76 if ((input != null) && input.isRequired()) { 77 writer.write(" <span class=\"req\">*</span>"); 78 } 79 80 writer.endElement("label"); 81 } 82 83 private boolean hasMessages(FacesContext context, UIComponent component) { 84 Iterator it = context.getClientIdsWithMessages(); 85 boolean found = false; 86 87 while (it.hasNext()) { 88 String id = (String ) it.next(); 89 90 if ((component != null) && id.equals(component.getClientId(context))) { 91 found = true; 92 break; 93 } 94 } 95 96 return found; 97 } 98 } 99 | Popular Tags |