Best approach to render UI elements based on dataType - jsf

I am trying to render richfaces and jsf UI elements dynamically based on the dataType value.
Ex : I have a enum as below
public enum DataType {
DT_LONGLONG(1), DT_STRING(2), DT_LONG(3), DT_DATE(4), DS_EXTERNALREFERENCE(5),
DT_BOOLEAN(6), DT_FLOAT(7), DT_SHORT(8);
}
Then in xhtml page while iterating through the list of my custom objects, I check for the dataType and render the UI elements accordingly as below :
<c:if test="#{meaCompPartAttr.dataType.dataType == 2}">
<h:inputText />
</c:if>
<c:if test="#{(meaCompPartAttr.dataType.dataType == 1) or
(meaCompPartAttr.dataType.dataType == 3) or
(meaCompPartAttr.dataType.dataType == 8)}">
<h:inputText onkeyup="javascript:validateField(this, '#{tpMsgs.longRegularExpression}');">
<f:validateLongRange/>
</h:inputText>
</c:if>
<c:if test="#{meaCompPartAttr.dataType.dataType == 7}">
<h:inputText onkeyup="javascript:validateField(this, '#{tpMsgs.doubleRegularExpression}');">
<f:validateDoubleRange/>
</h:inputText>
</c:if>
<c:if test="#{meaCompPartAttr.dataType.dataType == 6}">
<h:selectBooleanCheckbox />
</c:if>
<c:if test="#{meaCompPartAttr.dataType.dataType == 4}">
<rich:calendar />
</c:if>
Because of this I usually get class cast exceptions like String to Boolean or Long to String etc. I assume this is happening coz jstl and jsf code do not run in sync.
Is there any other approach to render UI elements dynamically as proposed in the above sample?

So you're iterating using <ui:repeat> or <h:dataTable> or any other JSF iterating component instead of the JSTL <c:forEach>? Either use <c:forEach> instead, or use the rendered attribute instead of <c:if>.
See also:
JSTL in JSF2 Facelets... makes sense?
How to create dynamic JSF form fields

Related

Evaluation with <c:when> in data table doesn't work

I have searched and tried but this time I'm really stuck.
I am trying to build a simple datatable (primefaces) where the cell content can be of different types. There is a holder class for each cell content that can hold different entities and I want to use < c:choose> to check and display the right entity in the entity specific way.
The code looks like:
<p:dataTable emptyMessage="" value="#{date.getThreadContent(column.propertyID)}" var="content">
<p:column>
#{content.type}
<c:choose>
<c:when test="#{content.type == 'activity'}">
#{content.activity.name}
</c:when>
<c:when test="#{content.type == 'todo'}">
#{content.activity.name}
</c:when>
<c:otherwise>
Neither activity or todo
</c:otherwise>
</c:choose>
</p:column>
</p:dataTable>
The EL evaluation doesn't work regardless if I try a boolean or String values in the bean (I'm using String value in the code above).
So each time the content is not empty, the output first displays the correct content type from #{content.type} but then together with 'Neither activity or todo'.
I can also say that this data table itself represents a cell content in a parent data table (list of entities per date) that is not visible in this code as I try to isolate the problem.
Could it be that this type of expression cannot be done in a ?
Any help is appreciated.
Use JSF rendered tags to do your conditional display logic, it removes it from the DOM completely and makes validations easier.
Refer: http://docs.oracle.com/javaee/6/tutorial/doc/bnaik.html for EL expressions
Also a good explanation is provided by BalusC here: JSTL c:if doesn't work inside a JSF h:dataTable
<p:dataTable emptyMessage="" value="#{date.getThreadContent(column.propertyID)}" var="content">
<p:column>
#{content.type}
<h:outputText value="#{content.activity.name}" rendered="#{content.type == 'activity' or content.type == 'todo'}" />
<h:outputText value="Neither activity or todo" rendered="#{content.type != 'activity' and content.type != 'todo'}" />
</p:column>
</p:dataTable>

<c:when test> evaluates always false

This is called 3 times, for each row once. (example table has 3 rows)
....
<ui:param name="rowIndex" value="#{cc.attrs.rowIndex}" />
<ui:param name="rowActive" value="#{cc.attrs.activeRow}" />
<c:set var="index" value="#{rowIndex}" type="java.lang.Long"/>
<c:set var="activeRowIndex" value="#{rowActive}" type="java.lang.Long"/>
<c:choose>
<c:when test="${index == 2}">
ACTIVE
</c:when>
<c:when test="${index != activeRowIndex}">
${index} - ${activeRowIndex} - INACTIVE
</c:when>
<c:otherwise>
NONE
</c:otherwise>
</c:choose>
....
Result:
0 - 1 - INACTIVE
1 - 1 - INACTIVE
2 - 1 - INACTIVE
I would have expected:
0 - 1 - INACTIVE
NONE
ACTIVE
I'm quite clueless why the result is so different from what i expected.
So i hope you can help me :-)
The variable names used suggests that you're using the composite inside a repeating component, such as <h:dataTable> or <ui:repeat>.
JSTL tags are executed during view build time, that moment when the JSF component tree is built based on XHTML source code. However, the var attribute of a repeating component is only available during view render time, that moment when the HTML output is produced based on JSF component tree.
In effects, at least the #{cc.attrs.rowIndex} is always null when JSTL runs.
When you're dependent on conditions which are only available during view render time, then you should be using the rendered attribute of a JSF component instead of JSTL <c:choose>/<c:if>.
E.g.
<c:set var="active" value="#{cc.attrs.rowIndex == 2}" />
<c:set var="inactive" value="#{not active and cc.attrs.rowIndex != cc.attrs.activeRow}" />
<c:set var="none" value="#{not active and not inactive}" />
<h:outputText value="ACTIVE" rendered="#{active}" />
<h:outputText value="#{index} - #{activeRowIndex} - INACTIVE" rendered="#{inactive}" />
<h:outputText value="NONE" rendered="#{none}" />
Note that this problem doesn't affect the <c:set>. It merely creates a EL variable mapping (an "alias"), it doesn't immediately evaluate the EL expression and store its result somewhere (as long as scope isn't definied). Also note that ${} and #{} behave exactly the same when Facelets is used instead of JSP. As the ${} is basically a heritage of legacy JSP, you should prefer exclusively using #{} to avoid confusion by yourself and your future maintainers.

How to show JSF components if list is not null and has size() > 0

How do I show JSF components if a list is not null and it has a size() > 0?
EL offers the empty operator which checks both the nullness and emptiness of an object.
Thus, this should do:
<h:dataTable value="#{bean.list}" var="item" rendered="#{not empty bean.list}">
No need for a clumsy double check on both null and size() as suggested by other answers.
See also:
How do I display a message if a jsf datatable is empty?
Conditionally displaying JSF components
use rendered attribute. most of the components have this attribute.This attribute;s main purpose is to render components conditionally.
<h:dataTable value="#{bean.list}" rendered="{bean.list !=null && bean.list.size()>0}" >
In the above piece of jsf code, datatable would only be rendered when list is not null and the size of list is greater than 0
<h:outputText value="No Data to Display!" rendered="#{empty list1.List2}" />
<a href="#">
<h:outputText value="Data is present" rendered="#{not empty list1.List2}" /></a>
Or
<h:outputText value="#{not empty list1.List2 ? 'Data is Present' : 'No Data to Display'}" style="color:blue"/>

JSF Compound EL expression

I am trying to validate a inputText box based on the selection of a CheckBox as shown below.
< <h:inputText required="#{param[facesContext.externalContext.response.namespace'form:checkBoxId']}"> >.
The issue is as you see, the component Ids are dynamic, I should be able to use facesContext.externalContext.response.namespace inside the EL expression. Is there a solution to it, appreciate any suggestions.
Thanks.
Just bind the UIComponent to a page scoped property and access its getValue() method.
<h:selectBooleanCheckbox binding="#{checkbox}" />
<h:inputText required="#{not empty checkbox.value and checkbox.value}" />
As to the dynamicness, you can also go around by just giving it a fixed id.
<h:form id="form">
<h:selectBooleanCheckbox id="checkbox" />
<h:inputText required="#{not empty param['form:checkbox'] and param['form:checkbox']}" />
</h:form>
It's however only ugly when it gets lengthy.

JSF: logic based on iteration index

Pardon me for the title, that's the best my limited brain can came up this late.
So, i have a list of string, something like [abc, def, ghi].
The question: in JSF, how do I iterate the list and create a string that look like this "abc, def, ghi" (notice the commas)?
For those who have the urge to tell me that I'd better use a Java method to concatenate the string, hear this: every member of the list should be rendered as a separate commandLink.
If plain JSF it would look like:
<h:commandLink>abc</h:commandLink>, <h:commandLink>def</h:commandLink>, <h:commandLink>ghi</h:commandLink>
Assuming that #{bean.items} returns List<String> or String[], in JSF 1.x you can use JSTL c:forEach with varStatus. It gives you a handle to LoopTagStatus which has a isLast() method.
<c:forEach items="#{bean.items}" var="item" varStatus="loop">
<h:commandLink value="#{item}" /><c:if test="#{!loop.last}">, </c:if>
</c:forEach>
In Facelets as shipped with JSF 2.x, same functionality is available by ui:repeat.
<ui:repeat value="#{bean.items}" var="item" varStatus="loop">
<h:commandLink value="#{item}" />#{!loop.last ? ', ' : ''}
</ui:repeat>

Resources