Caina Santos
Caina Santos

Reputation: 959

Calling an if function two times inside a jsf tag

Looking directly at the tag will be easier to understand my problem, the question goes inside the styleClass attribute:

<h:outputText value="#{prod.actualStock}" 
styleClass="
#{productBean.getSeverity(prod.actualStock, prod.replacementAlertLevel).equals('INFO') ?
'severity-info' : productBean.getSeverity(prod.actualStock, prod.replacementAlertLevel).equals('WARN') ?
'severity-warn' : 'severity-danger'}" />

Now, note that I'm calling two times the 'getSeverity()' function, each of the three returns gives a different style class for the outputText. Is there a way to call the function only once keeping the same logic?

The '' tag goes inside a table.

Upvotes: 1

Views: 427

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You can add another attribute in your ProductBean class that holds the result of ProductBean#getSeverity and you set it in your managed bean before using it in the <h:dataTable>

@ViewScoped
@ManagedBean
public class Bean {
    private List<ProductBean> productBean;
    //getters and setters...

    //I'm assuming you fill the list here
    @PostConstruct
    public void init() {
        productBean = ...
        for(ProductBean pb : productBean) {
            pb.setSeverityValue(pb.getSeverity(<parameters>));
        }
    }
}

In your JSF code, you just call the property

<h:outputText value="#{prod.actualStock}"
    styleClass="#{productBean.severityValue.equals('INFO') ? 'severity-info' : productBean.severityValue.equals('WARN') ? 'severity-warn' : 'severity-danger'}" />

Upvotes: 1

Jordan Denison
Jordan Denison

Reputation: 2727

Why not just have the getSeverity method return the class name as a string?

Upvotes: 0

Related Questions