Primefaces PickList Limit number of transferred elements - javascript

Salam,
I'm triying to implements a Primefaces PickList in my project, and i'm stuck with the max elements i have to transfer from source list to target :
in my case i want to trandfer max of 2 choices from a list of about 12 possible choices.
my selectChoice.xhtml looks like this :
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h1>Liste des cadres</h1>
</h:head>
<h:body>
<ui:composition template="../resources/template.xhtml">
<ui:define name="content">
<h:form>
<p:messages for="update"/>
<p:pickList id="pickList" value="#{etudiantController.pickFiliere}" var="filiere" itemLabel="#{filiere.intitule}" itemValue="#{filiere}" />
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
my managed bean is like this :
public List<Filiere> getListFiliere() {
listFiliere = filiereService.findAll();
return listFiliere;
}
public void setListFiliere(List<Filiere> listFiliere) {
this.listFiliere = listFiliere;
}
public DualListModel<Filiere> getPickFiliere() {
if (pickFiliere == null) {
pickFiliere = new DualListModel<Filiere>();
pickFiliere.setSource(getListFiliere());
}
return pickFiliere;
}
public void setPickFiliere(DualListModel<Filiere> pickFiliere) {
this.pickFiliere = pickFiliere;
}
public void onTransfer(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for(Object item : event.getItems()) {
builder.append(((Filiere) item).getIntitule()).append("<br />");
}
FacesMessage msg = new FacesMessage();
msg.setSeverity(FacesMessage.SEVERITY_INFO);
msg.setSummary("Items Transferred");
msg.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onSelect(SelectEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Item Selected", event.getObject().toString()));
}
public void onUnselect(UnselectEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Item Unselected", event.getObject().toString()));
}
public void onReorder() {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "List Reordered", null));
}
How to tell my PickList to disable transfer of elements after doing 2 transfer.
thanx
///////////////////**********************////////////////////////////////////////
switched to SelectManyCheckbox like melloware has suggested, because it seems more freindley for user to use checkbox, so my xhtml :
<p:selectManyCheckbox id="studentChoices" value="#{etudiantController.choixFLTmp}" layout="responsive" columns="3">
<f:selectItems value="#{filiereController.allFilieres}" var="filiere" itemLabel="#{filiere.intitule}" itemValue="#{filiere}" />
<f:validator validatorId="studentChoicesValidator" />
</p:selectManyCheckbox>
<p:message id="verifyMaxChoices" for="studentChoices"/>
i v created a validator based on balusC answers on this post : How to validate the maximum amount of checked values of a selectManyCheckbox based on the current selection of a selectOneMenu?
my Validator :
#FacesValidator("studentChoicesValidator")
public class StudentChoicesValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
List<Filiere> choixFLTmp = (List<Filiere>) value;
if (choixFLTmp.size() > 2) {
throw new ValidatorException(new FacesMessage(
FacesMessage.SEVERITY_ERROR, "Vous ne pouvez cochez plus que deux(2) choix !", null));
}
}
}
For now the message does not apear in my xhtml, and user can do more than 2 check.
How am i supposed to fire the validation(in my mind i always thinked that it fires automatically)
thanx.

Related

Spring On Submit Button textbox value keep unchanged but select tag getting empty

This is my PojoClass
package com.LoginPojo;
import org.hibernate.validator.constraints.NotEmpty;
public class LoginDeatils {
public String state;
public String district;
public String userName;
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
This is my JSP File :-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form action="login" method="POST" commandName="loginBean" accept-charset="UTF-8">
<table>
<tr>
<td>Name:<form:input id="userName" name="userName" path="userName" /><br></td>
<td align="left"><form:errors path="userName" cssClass="error"/></td>
</tr>
<tr>
<td>State: <form:select path="state" items="${stateList}" onchange="addDistrictValues()" /><br></td>
</tr>
<tr>
<td>District: <form:select path="district" /><br></td>
</tr>
</table>
<input type="submit" value="login"/>
</form:form>
<script type="text/javascript">
function addDistrictValues() {
document.getElementById("userName").value="abchd";
var x = document.getElementById("district");
var option = document.createElement("option");
option.text = "Raigad";
x.add(option);
}
</script>
</body>
</html>
This is my Controller:
package com.SelectTagPackage;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.LoginPojo.LoginDeatils;
import com.validator.LoginValidator;
#Controller
#RequestMapping("/login")
public class SelectTagController {
#Autowired
LoginValidator loginValidator;
public LoginValidator getLoginValidator() {
return loginValidator;
}
public void setLoginValidator(LoginValidator loginValidator) {
this.loginValidator = loginValidator;
}
#RequestMapping (method = RequestMethod.POST)
public ModelAndView loginPOST(#Valid #ModelAttribute("loginBean")LoginDeatils loginBean , BindingResult bindingResult,ModelMap map) throws Exception
{
loginValidator.validate(loginBean, bindingResult);
if (bindingResult.hasErrors()) {
return new ModelAndView("pageForSelectTag"); //JSP Page Name
}
else
{
System.out.println("bindingResult.hasErrors() else block");
return new ModelAndView("pageForSelectTag"); //JSP Page Name
}
}
#RequestMapping (method = RequestMethod.GET)
public ModelAndView loginGET(#Valid #ModelAttribute("loginBean")LoginDeatils loginBean , BindingResult bindingResult,ModelMap map) throws Exception
{
return new ModelAndView("pageForSelectTag");
}
#ModelAttribute("stateList")
public List loadprofessionList() {
List<String> stateList = new ArrayList<String>();
stateList.add("Maharashtra");
stateList.add("Keral");
return stateList;
}
}
This is my Validator Class :-
package com.validator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.LoginPojo.LoginDeatils;
#Component
public class LoginValidator implements Validator {
public boolean supports(Class<?> arg0) {
// TODO Auto-generated method stub
return LoginDeatils.class.isAssignableFrom(arg0);
}
public void validate(Object arg0, Errors errors) {
LoginDeatils objLoginDeatils=(LoginDeatils)arg0;
if(!objLoginDeatils.getUserName().equals("milind"))
{
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "error.userName", "userName is requiredddd.");
}
}
}
My Issue is :- whenever i am executing onchange event of state combo box 2 things happen
<td>State: <form:select path="state" items="${stateList}" onchange="addDistrictValues()" /><br></td>
1) addDistrictValues javascript method is getting called.
function addDistrictValues() {
document.getElementById("userName").value="abchd";
var x = document.getElementById("district");
var option = document.createElement("option");
option.text = "Raigad";
x.add(option);
}
setting abchd value to userName text box refer :-
document.getElementById("userName").value="abchd";
and 2nd Raigad value will get added into district select box JSP Code :-
<td>District: <form:select path="district" /><br></td>
javascript code :-
var x = document.getElementById("district");
var option = document.createElement("option");
option.text = "Raigad";
x.add(option);
but whenever i click on submit button i. e
<input type="submit" value="login"/>
controller loginPOST method getting called which internally calls validate method and form get loaded again
#RequestMapping (method = RequestMethod.POST)
public ModelAndView loginPOST(#Valid #ModelAttribute("loginBean")LoginDeatils loginBean , BindingResult bindingResult,ModelMap map) throws Exception
{
loginValidator.validate(loginBean, bindingResult);
if (bindingResult.hasErrors()) {
return new ModelAndView("pageForSelectTag"); //JSP Page Name
}
else
{
System.out.println("bindingResult.hasErrors() else block");
return new ModelAndView("pageForSelectTag"); //JSP Page Name
}
}
but when controller method with validate method calls textbox value "abchd" remains as it is on textbox but "Raigad" value which we have added through javascript[textbox value also set by javascript] will get vanish from select box
so why only select box value only getting vanish but textbox value remains unchange , both are setting by javascript.
plz help
enter image description here
enter image description here
enter image description here
i searched more in google but i am not getting any proper solution from any where
but when controller method with validate method calls textbox value "abchd" remains as it is on textbox but "Raigad" value which we have added through javascript[textbox value also set by javascript] will get vanish from select box
so why IN SPRING only select box value only getting vanish but textbox value remains unchange , both are setting by javascript.
Once u see the attached images ur doubt will gets clear
plz help
You are not providing a list of items for the "district" select control like what you are doing for the "state" select control. Try this in your Controller:
#ModelAttribute("districtMap")
public List loadDistrictMap() {
Map<String, String> districts new LinkedHashMap<String, String>();
districts.put("1", "1st District");
districts.put("2", "2nd District");
districts.put("3", "Raigad");
districts.put("n", "Nth District");
return districts;
}
And then in your JSP form:
<td>District: <form:select path="district" items="${districtMap}" /><br></td>
The district map is just an example list, it could come from a database or something but the point is that your controller should somehow provide the full list of possible districts options so that the select control can bind the correct one based on the "path" attribute.

Pass JavaScript Value from Webview to Activity?Android

I followed this to Print in android (Thermal Printer)
This is My web-view Over there On-click It will Load My Android Activity Which is Out of Web-view...
For that I have Given this... to Open new activity from web-view..
public class Main_web extends AppCompatActivity {
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_m);
webView = (WebView) findViewById(R.id.webm);
WebSettings set = webView.getSettings();
set.setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
final ProgressDialog progressBar = ProgressDialog.show(Main_web.this, "Please Wait", "Loading...");
webView.addJavascriptInterface(new WebAppInterface(this), "NewFUN");
webView.requestFocusFromTouch();
webView.setWebViewClient(new WebViewClient()
{
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
webView.setWebChromeClient(new WebChromeClient());
String url = "www.google.com/m_app_eta.php";
//String url = "file:///android_asset/tex.html";
try {
if (URLUtil.isValidUrl(url)) {
webView.loadUrl(url);
} else {
//do something
}
} catch (Exception e) {
//do something
}
}
//Class to be injected in Web page
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void Print() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure you want to leave to next screen?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent chnIntent = new Intent(Main_web.this, Print_activity.class);
startActivity(chnIntent);
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
}
Now My printer Activity is working Fine So here I want to pass a Value On click Button Which Opens Printer... But can Any one suggest me How to Receive same value in android Activity not in web-view...
All I need is In my web-view when I click on the Button its loading Android Activity Along with that I want to Pass A string value to new Activity
Why Should I pass Value means In that I have a Url so I can Print with that URL
Here JS value is different form current URL
Update
I followed this But its Inside the Web-view I want same at Outside the web-view...
Means When I click on the web-view Its opening android activity with the same its should pass a value to my activity not the web-view
Update 1
I followed #Sujal Mandal answer But I dont Know How to use that Value In next activity Can any one suggest me... on this kind... in next activity It may in System.out.println or text-view or any other string So I can use can Any one suggest How to Use the JavaScript Value in other activity outside the web-view..
HTML JS CODE
<script type="text/javascript">
function Pa(value) {
//value is the param received from onClick
NewFUN.Print(value); //call the android method with value param
}
</script>
<center>
<h3>Sample HTML</h3>
<div id="content">Click on Button To thermal print</div>
<div>
<input type="button" onClick="Pa('26997')" /><br/>
</div>
</center>
& change your android code to be like this
#JavascriptInterface
public void Print(final String stringFromWebView) {
//use stringFromWebView
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure you want to leave to next screen?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent chnIntent = new Intent(Main_web.this, Print_activity.class);
chnIntent.putExtra("STRING_DATA", stringFromWebView);
startActivity(chnIntent);
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
In next activity receive the web JS response by using
String data = getIntent().getStringExtra("STRING_DATA");
at oncreate

Using Javascript bridge in android

Im just trying to communicate my java app with the content on the webview .
In detail , may be just showing a toast on button click ?
After searching on google and doing some research , ended up with the following code .
P.S : - Im using Android Studio , is there any external library i need to compile inorder to get things done ? or something else ?
Following is my WebviewActivity code:-
public class WebviewActivity extends AppCompatActivity {
private static final String TAG = "Main";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
//WebView Object
WebView browser;
browser=(WebView)findViewById(R.id.webView);
//Enable Javascript
browser.getSettings().setJavaScriptEnabled(true);
//Inject WebAppInterface methods into Web page by having Interface 'Android'
browser.addJavascriptInterface(new WebAppInterface(this), "Android");
browser.loadUrl("http://www.somewebsite.com/app/form.html");
}
//Class to be injected in Web page
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/**
* Show Toast Message
* #param toast
*/
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
/**
* Show Dialog
* #param dialogMsg
*/
public void showDialog(String dialogMsg){
AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
// Setting Dialog Title
alertDialog.setTitle("JS triggered Dialog");
// Setting Dialog Message
alertDialog.setMessage(dialogMsg);
// Setting alert dialog icon
//alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(mContext, "Dialog dismissed!", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
/**
* Intent - Move to next screen
*/
public void moveToNextScreen(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("Alert");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to leave to next screen?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Move to Next screen
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Cancel Dialog
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
}
}
form.html:-
<html>
<head>
<style>
body{
background-color: #FA5858;
color:#fff;
}
input{
background-color: #F7D358;
width: 300px;
padding:10px;
color: #000;
}
div#content{
padding:20px;
background-color: #F7D358;
color: #000;
}
</style>
<script type="text/javascript">
function showAndroidToast(toastmsg) {
Android.showToast(toastmsg);
}
function showAndroidDialog(dialogmsg) {
Android.showDialog(dialogmsg);
}
function moveToScreenTwo() {
Android.moveToNextScreen();
}
</script>
</head>
<body>
<center>
<h3>Binding JavaScript code to Android code</h3>
<div id="content">
//some content here
</div>
<div>
Here are few examples:
</div>
<div>
<input type="button" value="Make Toast" onClick="showAndroidToast('Toast made by Javascript')" /><br/>
<input type="button" value="Trigger Dialog" onClick="showAndroidDialog('This dialog is triggered by Javascript ')" /><br/>
<input type="button" value="Take me to Next Screen" onClick="moveToScreenTwo()" />
</div>
</center>
</body>
</html>
I have this above code , but it is not working in android-studio , tried all posiblities so finally posted my question here .
My study for this :-
https://developer.android.com/guide/webapps/webview.html
https://developer.android.com/reference/android/webkit/WebView.html
http://stackoverflow.com/questions/4325639/android-calling-javascript-functions-in-webview
Your methods inside WebAppInterface class are missing the #JavascriptInterface annotation.
Your WebAppInterface class should be like this,
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showToast(String toast) {
}
#JavascriptInterface
public void showDialog(String dialogMsg){
}
#JavascriptInterface
public void moveToNextScreen(){
}
}
Edit
Don't forget to limit your app to API17+ when loading web content into the WebView, otherwise your App will be vulnerable to attacks. Read #Robert's comment below.
Thanks , this helped me. I made a working example:
here the zip for download:
http://www.mediafire.com/file/xyirbqdf73op7zs/file
https://www.b4x.com/android/forum/threads/webviewextras-send-data-from-webview-to-b4x-from-b4x-to-webview-addjavascriptinterface-callsub.121471/

For JavaFX's WebEngine, how do I get notified of javascript errors?

I'm trying to run some SVG that contains Javascript in JavaFX's WebView. I know some of the scripts I'm trying to run have errors and am trying to figure out how to print them to the console so I can debug them. I've tried the following, but the WebErrorEvent is never called:
WebEngine webEngine = browser.getEngine();
webEngine.setOnError(new EventHandler<WebErrorEvent>()
{
#Override
public void handle(WebErrorEvent event)
{
System.err.println(event);
}
});
Is this the right way to get javascript error feedback from this control?
setOnError listener only works for error while loading a given document.
One way to solve this is to call a Java method when console.log is called. You can do this by.
Your FX application
WebEngine engine = mainWebView.getEngine();
engine.load("http://whereever.com");
engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) {
JSObject window = (JSObject) engine.executeScript("window");
window.setMember("java", new Bridge());
engine.executeScript("console.log = function(message) { java.log(message); }"); // Now where ever console.log is called in your html you will get a log in Java console
}
});
Your Bridge class
public class Bridge {
public void exit() {
Platform.exit();
}
public void log(String text) {
System.out.println(text);
}
}
Your html
<h1>Text Page</h1>
<button onclick="java.log('This is log')">Log</button>
<button onclick="console.log('This produces the same result as above')">Console.log</button>
<button onclick="java.exit()">Exit</button>
Hope this is of some help.

How to make a single HTML page to choose different CSS stylesheet for the theme by using dropdown list

HTML code:
<h:panelGrid columns="2" cellpadding="10">
<h:outputText value="Color:"></h:outputText>
<p:themeSwitcher effect="fade" style="width:165px" id="color">
<f:selectItem itemLabel="Green" itemValue="href='#{request.contextPath}/theme/primefaces-aristo/theme.css" />
<f:selectItem itemLabel="Blue" itemValue="href='#{request.contextPath}/theme/primefaces-aristo/theme1.css" />
</p:themeSwitcher>
</h:panelGrid>
I create 2 different CSS stylesheet which are theme.css and theme1.css
The problem is when I select the theme1.css(label as Blue), it doesn't work and the theme still the same.
How to solve it? Any ideas?
UPDATE:
JAVA page:
private String csspath = "";
private String selectedCss = "Pink";
private boolean trigger_valuechange_refresh;
public Test() {
if(this.selectedCss.equals("Pink")) {
this.csspath = "/theme/primefaces-aristo/theme1.css";
} else {
this.csspath = "/theme/primefaces-aristo/theme.css";
}
}
public String getCsspath() {
return csspath;
}
public String getSelectedCss(){
return selectedCss;
}
public void setSelectedCss(String selectedCss){
this.selectedCss = selectedCss;
}
public void handleTest_combo_box_trans_groupValueChange() {
this.trigger_changeValue_refresh = true;
if (this.trigger_changeValue_refresh) {
if (_tg != null) {
getTransactActivityType_ByLogCategory(_tg);
}
this.trigger_changeValue_refresh = false;
}
}
HTML:
<h:outputStylesheet name="#{pc_Test.csspath}" value="#{pc_Test.csspath}" />
<p:selectOneMenu value="#{pc_Test.selectedCss}">
<p:ajax update="form1" listener="#{pc_Test.changeValue}"/>
<f:selectItem itemLabel="Green" itemValue="Green" />
<f:selectItem itemLabel="Pink" itemValue="Pink" />
This is my updated code. I have some problem on JAVA page which is the value change part.
Any idea to solve it?
I would use the following approach:
You manage the selected CSS in a ManagedBean and let the user choose his oder her desired style with a <p:selectOneMenu>. So your xhtml page looks like this:
<h:outputStylesheet library="css" name="#{myBean.stylesheet}" />
<p:selectOneMenu value="#{myBean.stylesheet}">
<p:ajax event="itemSelect" update="main" />
<f:selectItem itemLabel="Green" itemValue="theme.css" />
<f:selectItem itemLabel="Blue" itemValue="theme1.css" />
</p:selectOneMenu>
By using <p:ajax> you can trigger an update on whichever area (e.g. a surrounding <h:form id="main">) and apply the new styling. I don't know if itemSelect is the right event to listen to but you can find out by trying.
Your corresponding ManagedBean would look like the following:
#ManagedBean
#SessionScoped
public class MyBean {
private String stylesheet;
//getter and setter
}
This is only the approach I would take and therefore not tested. But this is a way it could work. Hope I could help you a little.
Personnaly i would use a managed bean in session scope for storing the user css choise.
#ManagedBean(name = "CSSManager")
#SessionScoped
public class CSSManager {
private String csspath = "";
private String selectedCss = "Blue";
public CSSManager() {
if(this.selectedCss.equals("Blue"))) {
this.csspath = "css/theme1.css";
} else {
this.csspath = "css/theme.css";
}
}
public void changeValue(){
}
public String getCsspath() {
return csspath;
}
public String getSelectedCss(){
return selectedCss;
}
public void setSelectedCss(String selectedCss){
this.selectedCss = selectedCss;
}
}
And inside your HTML code :
<h:outputStylesheet name="#{CSSManager.csspath}" value="#{CSSManager.csspath}" />
Don't forget to put your css file inside the WebContent/resources/css/ folder.
That should do the trick
Update :
<p:selectOneMenu value="#{CSSManager.selectedCss}">
<p:ajax update="Your Main Form" listener="#{CSSManager.changeValue}"/>
<f:selectItem itemLabel="Blue" itemValue="Blue" />
<f:selectItem itemLabel="Green" itemValue="Green" />
</p:selectOneMenu>

Categories