piątek, 25 lutego 2011

How to check if composite component's attribute is set?

Composite components are one of the nicest features of the facelets. They allow to easily bundle some parts of markup as reusable components.
One of the common problems with them is the inability to check if the actual attribute has been set on component usage. This has been partially solved in JSF 2.0 by allowing to set default value for an attribute but still it isn't perfect.
Here is my solution for this problem which is based on the observation how facelets pass values between different fragments of the markup.
Solution uses custom tag handler which will process its content only if the attribute with given name has been set for the composite component.

public class IfHasAttributeTagHandler extends TagHandler {
 private final TagAttribute name;

 public IfHasAttributeTagHandler(TagConfig config) {
  super(config);
  name = getRequiredAttribute("name");
 }

 public void apply(FaceletContext ctx, UIComponent parent)
  throws IOException, FacesException, ELException {
  if (ctx.getVariableMapper().resolveVariable(
   name.getValue(ctx)) != null) {
   nextHandler.apply(ctx, parent);
  }
 }
}

The sample usage of this component might look like this:

<c:set var="hasArg" value="false" />
<custom:ifHasAttribute name="arg">
  <c:set var="hasArg" value="true" />
</custom>

Of course in the similar way you can build component which will process its content only is the attribute hasn't been defined.

Brak komentarzy:

Prześlij komentarz