ThemeSwitcher

UI Components for JSF
f2pro
Posts: 51
Joined: 07 Jan 2011, 18:22
Location: Brazil
Contact:

30 Sep 2011, 21:44

Hello.

I followed the same example in the website that uses the GuestPreferences to set the theme on the session I guess.
But it doesn't worked well.
It changes the theme but, when I press F5 the theme turns to the original.

See my code:

ThemeSwitcherMB - Manange Bean

Code: Select all

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mb;

import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;
import util.GuestPreferences;

/**
 *
 * @author Fabricio
 */
@Named(value = "themeSwitcherMB")
@SessionScoped
public class ThemeSwitcherMB implements Serializable {

    private Map<String, String> themes;
    private String theme;
    private GuestPreferences gp = new GuestPreferences();

    public void setGp(GuestPreferences gp) {
        this.gp = gp;
    }

    public Map<String, String> getThemes() {
        return themes;
    }

    public String getTheme() {
        return theme;
    }

    public void setTheme(String theme) {
        this.theme = theme;
    }

    /** Creates a new instance of ThemeSwitcherMB */
    public ThemeSwitcherMB() {

        theme = gp.getTheme();
        gp.setTheme("blitzer");

        themes = new TreeMap<String, String>();
        themes.put("Aristo", "aristo");
        themes.put("Blitzer", "blitzer");
        themes.put("Smoothness", "smoothness");
        themes.put("Start", "start");
        themes.put("UI-Lightness", "ui-lightness");
        themes.put("Vader", "vader");
    }

    public void saveTheme() {
        System.out.println("theme: " + theme);
        gp.setTheme(theme);
    }
}

cadPersonal.xhtml - View

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition template="#{pageContext.request.contextPath}/template/template.xhtml" 
                xmlns="http://www.w3.org/1999/xhtml"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:p="http://primefaces.org/ui"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:h="http://java.sun.com/jsf/html">

    <ui:define name="content">
        <p:panel id="conteudo">
            <p:messages id="msgConfig" globalOnly="true"/>

            <h:form id="formDados">

                <p:panel style="border: none; padding: 0px; margin: 0px;">
                    <p:growl id="msgs"/>
                </p:panel>

                <p:panel header="Configuração - Personal" 
                         style="padding: 0px; margin: 0px;">
                    <p:panel>
                        <h:panelGrid columns="2">
                            <h:outputLabel value="Escolha um tema: "/>
                            <p:themeSwitcher value="#{themeSwitcherMB.theme}" style="width:150px" effect="fade">  
                                <f:selectItem itemLabel="Choose Theme" itemValue="" />  
                                <f:selectItems value="#{themeSwitcherMB.themes}" />  
                                <p:ajax listener="#{themeSwitcherMB.saveTheme}" />  
                            </p:themeSwitcher> 
                        </h:panelGrid>
                    </p:panel>
                </p:panel>

                <br/>

                <p:commandButton image="ui-icon ui-icon-disk"
                                 value="Gravar"
                                 action="#{configValidacaoMB.cadastraConfig}"
                                 update="formDados"
                                 process="formDados"
                                 oncomplete="
                                 if(args.sucesso == true) {
                                 self.location= '../home/index.xhtml';
                                 }                                 
                                 "
                                 onstart="showLoading('formDados:imagemP2');"
                                 onsuccess="hideLoading('formDados:imagemP2');"/>
                <p:graphicImage id="imagemP2" value="/imagens/ajaxloading.gif" style="margin-left: 10px; display: none;"/>

                <p:commandButton image="ui-icon ui-icon-cancel"
                                 value="Cancelar"
                                 process="@this"
                                 oncomplete="self.location= '../home/index.xhtml';"
                                 onstart="showLoading('formDados:imagemP1');"
                                 onsuccess="hideLoading('formDados:imagemP1');"/>
                <p:graphicImage id="imagemP1" value="/imagens/ajaxloading.gif" style="margin-left: 10px; display: none;"/>

            </h:form>

        </p:panel>
    </ui:define>

</ui:composition>
The class GuestPreferences.java

Code: Select all

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

/**
 *
 * @author Fabricio
 */
import java.io.Serializable;
import java.util.Map;

import javax.faces.context.FacesContext;

public class GuestPreferences implements Serializable {

        private String theme = "vader"; //default

        public String getTheme() {
                Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
                if(params.containsKey("theme")) {
                        theme = params.get("theme");
                }
                
                return theme;
        }

        public void setTheme(String theme) {
                this.theme = theme;
        }
}

And my web.xml I have this

Code: Select all

...
    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>smoothness</param-value>
    </context-param>
..
What's wrong?

Cool Mr Ice
Posts: 46
Joined: 17 Sep 2011, 11:53

30 Sep 2011, 22:57

I discovered the same thing while trying to use the Showcase's code. It drove me crazy for a week. Hopefully you can be saved from that experience. Notice that when you refresh the showcase example ( http://www.primefaces.org/showcase-labs ... itcher.jsf ) or navigate to another page, the theme is lost. 2.2.1 keeps the theme on refresh. If the intent of the code behind the showcase example is to keep the theme after refresh or navigation then I would say that it is a bit overwritten and does not work as intended. A month ago I could tell you exactly what the problem was, but what I do remember is that the GuestPreferences class seemed buggy and unnecessary. So, I will share with you what I came up with, and you can feel free to use it, alter it, or ignore it.

web.xml

Code: Select all

    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>#{sessionManager.theme}</param-value>
    </context-param>
template.xhtml <---my p:themeSwitcher is defined in a template that most pages use. It is obviously not necessary to place p:themeSwitcher in a template.

Code: Select all

        <f:metadata>
           <f:event type="preRenderView" listener="#{sessionManager.preRenderView}"></f:event>
        </f:metadata>

                                    <p:themeSwitcher value="#{sessionManager.theme}" style="min-width:150px; text-align:left;" effect="fade" var="t">
                                        <f:selectItems value="#{sessionManager.themes}" var="theme" itemLabel="Theme: #{theme.displayName}" itemValue="#{theme}"/>
                                        <p:column>
                                            <p:graphicImage value="/images/themes/#{t.image}"/>
                                        </p:column>
                                        <p:column>
                                            #{t.displayName} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                        </p:column>
                                        <p:ajax/>
                                    </p:themeSwitcher>
SessionManager.java --this class may be a bit overkill for you. Rather than me stripping out stuff you don't need - I will leave that pleasure for you. What I am doing is saving the theme the user selects to the database so that when they return for another session, it will be as they left it. You don't have to do that. As long as the theme is saved in a SessionScoped bean, your theme will be preserved (but only for the duration of the current session). Also, feel free to criticize my usage of JPA -- I freely admit, I have no idea how to use JPA appropriately - still learning.

Code: Select all

package jsf.util;

import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletException;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import jpa.entities.TUser;

@ManagedBean (name="sessionManager")
@SessionScoped
public class SessionManager implements Serializable
{
    @PersistenceContext(unitName = "ServiceTracePU")
    private EntityManager entityManager;
    private String theme = JsfUtil.DEFAULT_THEME;
    private boolean isSessionUserInfoSet = false;
    private int userSKey;
    private String userName;
    private String firstName;
    private String lastName;
    
    public void preRenderView(ComponentSystemEvent event)
    {
        if(this.isSessionUserInfoSet)
            return;

        setSessionUserInfo();
        this.isSessionUserInfoSet = true;
    }

    private void setSessionUserInfo()
    {
        this.userName = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();

        try
        {
            TUser user = (TUser) entityManager.createNamedQuery("TUser.findByUsername").setParameter("username", userName).getSingleResult();
            this.userSKey = user.getUserskey();
            this.firstName = user.getFirstname();
            this.lastName = user.getLastname();
            this.theme = user.getTheme() == null ? JsfUtil.DEFAULT_THEME : user.getTheme();
        }
        catch (NoResultException nre)
        {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "User information not found.", "Please see someone.");
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }

    public List<Theme> getThemes() {
        return JsfUtil.THEMES;
    }
     
    public String getTheme() {
        return theme;
    }

    public void setTheme(String theme) {
        if(theme == null)
            theme = JsfUtil.DEFAULT_THEME;
        
        if(this.theme.equals(theme))
            return;
        
        this.theme = theme;
        
        UserTransaction transaction = null;
        
        try {
            transaction = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
            transaction.begin();
            entityManager.joinTransaction();
            
            Query updateUserTheme = entityManager.createNamedQuery("TUser.updateTheme");
            updateUserTheme.setParameter("theme", theme);
            updateUserTheme.setParameter("updateuserskey", new TUser(this.userSKey));
            updateUserTheme.setParameter("userskey", this.userSKey);
            int rowsUpdated = updateUserTheme.executeUpdate();

            if(rowsUpdated != 1) {
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "User theme was not correctly updated", "Notify admin");
                FacesContext.getCurrentInstance().addMessage(null, message);
                transaction.rollback();
            }
            
            transaction.commit();
        }
        catch (NamingException | NotSupportedException | SystemException | IllegalStateException | SecurityException | javax.transaction.RollbackException | HeuristicMixedException | HeuristicRollbackException e) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error Setting User's Theme", e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, message);
            
            try {
                transaction.rollback();
            }
            catch (IllegalStateException | SecurityException | SystemException e2) {
                message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error Rolling Back Transaction", e2.getMessage());
                FacesContext.getCurrentInstance().addMessage(null, message);                
            }
        }
    }
    
    public String logout()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

        try
        {
            request.logout();
        }
        catch (ServletException e)
        {
            context.addMessage(null, new FacesMessage("Logout failed!"));
        }

        context.getExternalContext().invalidateSession();

        return "/login.xhtml?failed=false?faces-redirect=true";
    }

    public int getUserSKey()
    {
        return userSKey;
    }

    public String getUserName()
    {
        return userName;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public String getWelcomeMessage()
    {
        return "Welcome, " + this.firstName + " " + this.lastName;
    }
}
Theme.java

Code: Select all

package jsf.util;
  
import java.io.Serializable;

public class Theme implements Serializable {
    private String name;
    private String displayName;
    private String image;
   
    public Theme() {
    }

    public Theme(String name, String displayName, String image) {
        this.name = name;
        this.displayName = displayName;
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    @Override
    public String toString() {
        return name;
    }
}
JsfUtil.java --a static list of available themes is kept in this class along with the system's default theme

Code: Select all

    public static final String DEFAULT_THEME = "aristo";
    public static final List<Theme> THEMES;
    static {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("/resources/Bundle");
        THEMES = new ArrayList<>();
        THEMES.add(new Theme("aristo", resourceBundle.getString("aristo"), "aristo.png"));
        THEMES.add(new Theme("black-tie", resourceBundle.getString("black-tie"), "black-tie.png"));
        THEMES.add(new Theme("blitzer", resourceBundle.getString("blitzer"), "blitzer.png"));
        THEMES.add(new Theme("bluesky", resourceBundle.getString("bluesky"), "bluesky.png"));
        THEMES.add(new Theme("casablanca", resourceBundle.getString("casablanca"), "casablanca.png"));
        THEMES.add(new Theme("cupertino", resourceBundle.getString("cupertino"), "cupertino.png"));
        THEMES.add(new Theme("dark-hive", resourceBundle.getString("dark-hive"), "dark-hive.png"));
        THEMES.add(new Theme("dot-luv", resourceBundle.getString("dot-luv"), "dot-luv.png"));
        THEMES.add(new Theme("eggplant", resourceBundle.getString("eggplant"), "eggplant.png"));
        THEMES.add(new Theme("excite-bike", resourceBundle.getString("excite-bike"), "excite-bike.png"));
        THEMES.add(new Theme("flick", resourceBundle.getString("flick"), "flick.png"));
        THEMES.add(new Theme("glass-x", resourceBundle.getString("glass-x"), "glass-x.png"));
        THEMES.add(new Theme("hot-sneaks", resourceBundle.getString("hot-sneaks"), "hot-sneaks.png"));
        THEMES.add(new Theme("humanity", resourceBundle.getString("humanity"), "humanity.png"));
        THEMES.add(new Theme("le-frog", resourceBundle.getString("le-frog"), "le-frog.png"));
        THEMES.add(new Theme("midnight", resourceBundle.getString("midnight"), "midnight.png"));
        THEMES.add(new Theme("mint-choc", resourceBundle.getString("mint-choc"), "mint-choc.png"));
        THEMES.add(new Theme("overcast", resourceBundle.getString("overcast"), "overcast.png"));
        THEMES.add(new Theme("pepper-grinder", resourceBundle.getString("pepper-grinder"), "pepper-grinder.png"));
        THEMES.add(new Theme("redmond", resourceBundle.getString("redmond"), "redmond.png"));
        THEMES.add(new Theme("rocket", resourceBundle.getString("rocket"), "rocket.png"));
        THEMES.add(new Theme("smoothness", resourceBundle.getString("smoothness"), "smoothness.png"));
        THEMES.add(new Theme("south-street", resourceBundle.getString("south-street"), "south-street.png"));
        THEMES.add(new Theme("start", resourceBundle.getString("start"), "start.png"));
        THEMES.add(new Theme("sunny", resourceBundle.getString("sunny"), "sunny.png"));
        THEMES.add(new Theme("swanky-purse", resourceBundle.getString("swanky-purse"), "swanky-purse.png"));
        THEMES.add(new Theme("trontastic", resourceBundle.getString("trontastic"), "trontastic.png"));
        THEMES.add(new Theme("ui-darkness", resourceBundle.getString("ui-darkness"), "ui-darkness.png"));
        THEMES.add(new Theme("ui-lightness", resourceBundle.getString("ui-lightness"), "ui-lightness.png"));
        THEMES.add(new Theme("vader", resourceBundle.getString("vader"), "vader.png"));
    }
Bundle.properties <-- what the user sees in the list is kept here. JsfUtil above uses it

Code: Select all

aristo=Aristo
black-tie=Black Tie
blitzer=Blitzer
bluesky=Blue Sky
casablanca=Casablanca
cupertino=Cupertino
dark-hive=Dark Hive
dot-luv=Dot Luv
eggplant=Eggplant
excite-bike=Excite Bike
flick=Flick
glass-x=Glass X
hot-sneaks=Hot Sneaks
humanity=Humanity
le-frog=Le Frog
midnight=Midnight
mint-choc=Mint Chocolate
overcast=Overcast
pepper-grinder=Pepper Grinder
redmond=Redmond
rocket=Rocket
smoothness=Smoothness
south-street=South Street
start=Start
sunny=Sunny
swanky-purse=Swanky Purse
trontastic=Trontastic
ui-darkness=UI Darkness
ui-lightness=UI Lightness
vader=Vader
I have also downloaded and added to the project all of the relevant theme .jar and image .png files. Hopefully I didn't leave anything out. Good Luck!
PrimeFaces 3.5
JSF 2.1
Mojarra 2.1.3
Glassfish 3.1.1
Netbeans 7.0.1
JDK 7
JEE 6

f2pro
Posts: 51
Joined: 07 Jan 2011, 18:22
Location: Brazil
Contact:

03 Oct 2011, 13:49

Ok!
It Works, but I don't know how! hehehehe...
I can't understand how you can change a value in a xml file, but, if worked is fine hehe

cagatay.civici
Prime
Posts: 18616
Joined: 05 Jan 2009, 00:21
Location: Cybertron
Contact:

03 Oct 2011, 15:08

3.x has a brand new themeswitcher that changes theme with no page refresh. Can be stateful and stateless depending on your implementation.

Cool Mr Ice
Posts: 46
Joined: 17 Sep 2011, 11:53

03 Oct 2011, 18:23

optimus.prime wrote:3.x has a brand new themeswitcher that changes theme with no page refresh. Can be stateful and stateless depending on your implementation.
My example is 3.0.M3, and I do like the 3.x version much more than the 2.2.1 implementation. The theme definitely changes with no refresh (AJAX works great). As for stateful vs stateless, I've only tested this with a SessionScoped bean and it works great as well.

I do need to make a correction on my remarks regarding GuestPreferences. GuestPreferences is SessionScoped. It contains the the member variable of the current theme. Web.xml looks to GuestPreferences.theme to set/maintain the theme. If ThemeSwitcherBean (RequestScoped) in the showcase themeSwitcher example successfully sets GuestPreferences.theme, one would think that for the duration of the session that theme would be set regardless of the user navigating or refreshing. But, obviously that is not the case when testing in the 3.0 Showcase. I noticed, however, that the theme menu defined in the themeMenu.xhtml ui:composition which exists on the top left side in all of the showcase examples sets GuestPreferences.theme as well. So my guess is that this is the reason for refresh and navigation causing the selected theme to be lost when testing the themeSwitcher in the showcase.

Still though, It will always haunt me that I was never able to successfully replicate the showcase example using the code as is (problems with the ThemeSwitcherBean successfully setting and saving GuestPreferences.theme). It probably just amounts to some issue on my side of the fence.
PrimeFaces 3.5
JSF 2.1
Mojarra 2.1.3
Glassfish 3.1.1
Netbeans 7.0.1
JDK 7
JEE 6

AliasJava
Posts: 1
Joined: 26 Jul 2012, 16:23

26 Jul 2012, 16:47

To make ThemeSwitcher work perfectly you need to specify your bean theme in your web.xml so that after a refresh or a redirect the last choosen theme will be reloaded :P

Code: Select all

	<context-param>
		<param-name>primefaces.THEME</param-name>
		<param-value>#{themeSwitcherBean.theme}</param-value>
	</context-param> 
I have a themeSwitcherBean :

Code: Select all

import java.util.Map;
import java.util.TreeMap;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "themeSwitcherBean")
@ViewScoped
public class ThemeSwitcherBean {

	private Map<String, String> themes;

	private String theme= "bluesky";

	public Map<String, String> getThemes() {
		return themes;
	}

	public String getTheme() {
		return theme;
	}

	public void setTheme(String theme) {
		this.theme = theme;
	}

	@PostConstruct
	public void init() {

		themes = new TreeMap<String, String>();
		themes.put("Aristo", "aristo");
		themes.put("Black-Tie", "black-tie");
		themes.put("Blitzer", "blitzer");
		themes.put("Bluesky", "bluesky");
		themes.put("Casablanca", "casablanca");
		themes.put("Cupertino", "cupertino");
		themes.put("Dark-Hive", "dark-hive");
		themes.put("Dot-Luv", "dot-luv");
		themes.put("Eggplant", "eggplant");
		themes.put("Excite-Bike", "excite-bike");
		themes.put("Flick", "flick");
		themes.put("Glass-X", "glass-x");
		themes.put("Hot-Sneaks", "hot-sneaks");
		themes.put("Humanity", "humanity");
		themes.put("Le-Frog", "le-frog");
		themes.put("Midnight", "midnight");
		themes.put("Mint-Choc", "mint-choc");
		themes.put("Overcast", "overcast");
		themes.put("Pepper-Grinder", "pepper-grinder");
		themes.put("Redmond", "redmond");
		themes.put("Rocket", "rocket");
		themes.put("Sam", "sam");
		themes.put("Smoothness", "smoothness");
		themes.put("South-Street", "south-street");
		themes.put("Start", "start");
		themes.put("Sunny", "sunny");
		themes.put("Swanky-Purse", "swanky-purse");
		themes.put("Trontastic", "trontastic");
		themes.put("UI-Darkness", "ui-darkness");
		themes.put("UI-Lightness", "ui-lightness");
		themes.put("Vader", "vader");
	}

}
My jsf code:

Code: Select all

    <h:form>
					<p:themeSwitcher style="width:165px" id="defaultSwitcher" value="#{themeSwitcherBean.theme}">
						<f:selectItem itemLabel="Choose Theme" itemValue="" />
						<f:selectItems value="#{themeSwitcherBean.themes}" />
					</p:themeSwitcher>
				</h:form>
I'm using JSF 2 + Primefaces3.1.1 + Spring 3.1.1.RELEASE + Apache Tomcat 6.0.18 + MAVAN 3
INFO : I'm using also a different EL-IMPL then the one included in tomcat. I added a dependencies to my project to be able to use el-impl of JBOSS so that I can call Actions on my managed beans

Code: Select all

	<dependency>
			<groupId>org.glassfish.web</groupId>
			<artifactId>el-impl</artifactId>
			<version>2.2</version>
		</dependency>
AYMEN AMARA
JAVA J2EE ARCHTECTURE AND DEVELOPMENT

nokiajavi
Posts: 61
Joined: 24 Feb 2013, 15:03
Location: España
Contact:

24 Feb 2013, 15:08

Hello Good for all.

I'm using the 3.4.2 version of primefaces, I used the code that has been the companion "AliasJava" above. Changing the theme is done correctly and without reloading the page, but then I will upgrade or another page and returns to the default theme.

This same thing happens when you try to change the language of the application to reload or change to another site and you change the default language. Can anyone help me please?

thank you very much

legrandhuit
Posts: 4
Joined: 20 Dec 2012, 18:23

26 Mar 2013, 17:42

Hello,

I have the same problem with the themeswitcher component.
The theme is switch correctly in the current page, but when I navigate in an other page, I come back to the default theme.

Tested with Primefaces 3.4.2 and 3.5.

If you got an idea?

Thank you

nokiajavi
Posts: 61
Joined: 24 Feb 2013, 15:03
Location: España
Contact:

26 Mar 2013, 19:10

legrandhuit wrote:Hello,

I have the same problem with the themeswitcher component.
The theme is switch correctly in the current page, but when I navigate in an other page, I come back to the default theme.

Tested with Primefaces 3.4.2 and 3.5.

If you got an idea?

Thank you
Now I have the solution, at least to me has worked. I go on to describe as I have configured the ThemeSwitcher for you can use it just like me.

With this solution, when you change the theme of your application using a combobox automatically changes all primerfaces components without reloading the page. In addition to going to any other page on your site or reload it continues to be applied the last item selected in the combobox.

NOTE:
I am using a template for my website, where I place the form ThemeSwitcher. Then all my files .xhtml are including that template.

code of plantilla.xhtml

Code: Select all

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">

<h:head>
</h:head>
<h:body>
       <f:view>
           <h:form>
               <h:outputText value="Cambiar Tema:"></h:outputText>
               <p:themeSwitcher effectSpeed="normal" effect="fold" style="width:165px" id="defaultSwitcher" value="#{themeSwitcherBean.theme}">
                  <f:selectItem itemLabel="Cambiar Tema" itemValue="" />
                  <f:selectItems value="#{themeSwitcherBean.themes}" />
                  <p:ajax global="false" listener="#{themeSwitcherBean.saveTheme}" />
               </p:themeSwitcher>
           </h:form>
      <f:view>
</h:body>
</html>

Content index.xhtml (All my .xhtml files have this code)


With this line I make all my pages include the form of the change of theme.

Code: Select all

<h:body>
<ui:composition template="/plantilla/plantilla.xhtml">
......
......
<h:body>

Code of web.xml

Code: Select all

<context-param>
	<param-name>primefaces.THEME</param-name>
	<param-value>#{themeSwitcherBean.theme}</param-value>
  </context-param>
Code of ThemeSwitcherBean.java

Code: Select all

package com.beans;

import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;

import org.primefaces.component.themeswitcher.ThemeSwitcher;

@ManagedBean(name = "themeSwitcherBean")
@SessionScoped
public class ThemeSwitcherBean implements Serializable{

   /**
	 * 
	 */
	private static final long serialVersionUID = 7448888248791054139L;

private Map<String, String> themes;

   private String theme= "south-street";

   public Map<String, String> getThemes() {
      return themes;
   }

   public String getTheme() {
      return theme;
   }

   public void setTheme(String theme) {
      this.theme = theme;
   }

   @PostConstruct
   public void init() {

      themes = new TreeMap<String, String>();
      themes.put("Aristo", "aristo");
      themes.put("Black-Tie", "black-tie");
      themes.put("Blitzer", "blitzer");
      themes.put("Bluesky", "bluesky");
      themes.put("Casablanca", "casablanca");
      themes.put("Cupertino", "cupertino");
      themes.put("Dark-Hive", "dark-hive");
      themes.put("Dot-Luv", "dot-luv");
      themes.put("Eggplant", "eggplant");
      themes.put("Excite-Bike", "excite-bike");
      themes.put("Flick", "flick");
      themes.put("Glass-X", "glass-x");
      themes.put("Hot-Sneaks", "hot-sneaks");
      themes.put("Humanity", "humanity");
      themes.put("Le-Frog", "le-frog");
      themes.put("Midnight", "midnight");
      themes.put("Mint-Choc", "mint-choc");
      themes.put("Overcast", "overcast");
      themes.put("Pepper-Grinder", "pepper-grinder");
      themes.put("Redmond", "redmond");
      themes.put("Rocket", "rocket");
      themes.put("Sam", "sam");
      themes.put("Smoothness", "smoothness");
      themes.put("South-Street", "south-street");
      themes.put("Start", "start");
      themes.put("Sunny", "sunny");
      themes.put("Swanky-Purse", "swanky-purse");
      themes.put("Trontastic", "trontastic");
      themes.put("UI-Darkness", "ui-darkness");
      themes.put("UI-Lightness", "ui-lightness");
      themes.put("Vader", "vader");
   }

   public void saveTheme(AjaxBehaviorEvent ajax)
   {
	   setTheme((String) ((ThemeSwitcher)ajax.getSource()).getValue());
   }
}
in WEB-INF/lib

Code: Select all

all-themes-1.0.9.jar
primefaces-3.4.2.jar

Good luck, I hope it will be helpful

NOTE 1:

My main problem was that my class ThemeSwitcherBean.java, for some reason I do not was picking well the attribute "@ sessionScope" then the theme was never fixed.

Make a Clean your project and tomcat server to remove data from cache

legrandhuit
Posts: 4
Joined: 20 Dec 2012, 18:23

27 Mar 2013, 16:15

Wahou!

Your post is very complete and it helps me a lot!

In my project, I work with a template like you.

I have replace the "saveTheme" method with yours versions (with the ajax behaviors) and add a specific form for the themeswitcher component.

And now it works!

Thank you very much!

Post Reply

Return to “PrimeFaces”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 6 guests