nurgasemetey
nurgasemetey

Reputation: 770

Changing dynamically background color of commandbutton

I want to change color dynamically of commandbutton in Primefaces.

Here's code excerpt of commandbutton:

<p:commandButton id="movieBtn" value="#{kkcIncomingErrorBean.counter}" 
type="button" onclick="PF('errorTable').show()" 
styleClass="#{kkcIncomingErrorBean.buttonStyle}"/>

buttonStyle is field of kkcIncomingErrorBean class:

private String buttonStyle="background-color:red";
...
public String getButtonStyle() {
    return buttonStyle;
}

public void setButtonStyle(String buttonStyle) {
    this.buttonStyle = buttonStyle;
}

It is interesting that on update counter variable is updated but buttonStyle is not updated.

Do you have any ideas to fix this?

With regards

Upvotes: 1

Views: 7289

Answers (1)

BalusC
BalusC

Reputation: 1108652

You're confusing style with styleClass.

The style attribute should be used to declare individual CSS properties like as you currently have tight-coupled in your model.

The styleClass attribute can only be used to declare CSS class names which are in turn declared in a normal CSS file with the properties. It ultimately renders as a HTML class attribute, which you should have noticed if you peeked around in JSF-generated HTML output.

So you've 2 options:

  1. Use the style attribute.

    <p:commandButton ... style="#{kkcIncomingErrorBean.buttonStyle}" />
    
  2. Use a CSS class name instead.

    private String buttonStyle = "error";
    

    with the below class declaration in a normal CSS file which you include via <h:outputStylesheet>.

    .error {
        background: red;
    }
    

    By the way, that setter is unnecessary.

Of course, a normal CSS class name as shown in option 2 is preferred. CSS properties doesn't belong in a Java file, but in a CSS file.

Upvotes: 3

Related Questions