While selecting a dropdown,the second drop down values are not coming properly.I am attaching the code here
xhtml file:
<?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="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<f:event listener="#{userData.handleEvent}" type="preRenderView" />
</h:head>
<h:body>
<f:view>
<h:form >
<table>
<tr>
<td> <h:messages showDetail="true" /> </td>
</tr>
<tr>
<td><h:outputText value="Enter name : "/></td>
<td><h:inputText value="#{userData.clientname}"/></td>
</tr>
<tr>
<td><h:outputText value="Enter Id : " /></td>
<td><h:inputText value="#{userData.id}" /></td>
</tr>
<tr>
<td></td>
<td><h:commandButton value="Insert" action="#{userData.add}"/></td>
</tr>
<tr>
<td></td>
<td>#{userData.data}</td>
</tr>
<tr>
<td><h:selectOneRadio value="#{authorData.favColor1}" id="div2">
<f:selectItem itemValue="Red" itemLabel="Color1 - Red" />
<f:selectItem itemValue="Green" itemLabel="Color1 - Green"/>
<f:ajax event="click" binding="valbinding" execute="#form" render=":div1" listener="#{authorData.setchangeval}"/>
</h:selectOneRadio></td>
</tr>
</table>
</h:form>
<h:panelGroup id="div1" style="display: #{authorData.valdisplay};">
<span>
You have selected #{authorData.message}
</span>
</h:panelGroup>
</f:view>
<br/>
<h:outputLabel value="Choose your Car: * " for="firstdropdwn" />
<h:selectOneMenu id="firstdropdwn" value="#{authorData.favoriteCar2}">
<f:selectItems value="#{authorData.car4List}" var="d"
itemLabel="#{d.carlabel}" itemValue="#{d.carvalue}"/>
<f:ajax event="click" binding="valbinding1" execute="#this firstdropdwn" render=":seconddrpdown" listener="#{authorData.setDropDwnVal}"/>
</h:selectOneMenu>
<br/>
<h:outputLabel value="Choose your Owner: * " for="seconddrpdown" />
<h:selectOneMenu id="seconddrpdown" value="">
<f:selectItems value="#{authorData.car3List}" var="c"
itemLabel="#{c.carlabel}" itemValue="#{c.carvalue}"/>
</h:selectOneMenu>
</h:body>
</html>
Author.java:
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.ComponentSystemEvent;
#ManagedBean(name = "authorData", eager = true)
#SessionScoped
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
String clientname;
String id;
String favColor1;
public String favoriteCar2;
private UIComponent valbinding;
private UIComponent valbinding1;
public List<Car> car3List;
/*public Car[] getFavoriteCar3Value()
{
car3List = new Car[3];
car3List[0] = new Car("BMW Series 4 - 316", "316");
car3List[1] = new Car("BMW Series 4 - 318", "318");
car3List[2] = new Car("BMW Series 4 - 320", "320");
return car3List;
}
*/
public List<Car> getCar3List() {
return car3List;
}
public void setCar3List(List<Car> car) {
this.car3List = car;
}
public List<Car> car4List;
public List<Car> getCar4List() {
car4List = new ArrayList<Car>();
car4List.add(new Car("BMW","116"));
car4List.add(new Car("AUDI","118"));
car4List.add(new Car("MERCEDES","120"));
return car4List;
}
public UIComponent getValbinding1() {
return valbinding1;
}
public void setValbinding1(UIComponent valbinding1) {
this.valbinding1 = valbinding1;
}
private String valdisplay="none";
private String message;
public String getFavoriteCar2() {
return favoriteCar2;
}
public void setFavoriteCar2(String favoriteCar2) {
this.favoriteCar2 = favoriteCar2;
}
private static Map<String, String> favoriteCar2Value;
static
{
favoriteCar2Value = new LinkedHashMap<String, String>();
favoriteCar2Value.put("BMW Series 1 - 116", "116"); //label, value
favoriteCar2Value.put("BMW Series 1 - 118", "118");
favoriteCar2Value.put("BMW Series 1 - 120", "120");
}
public Map<String, String> getFavoriteCar2Value()
{
return favoriteCar2Value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getValdisplay() {
return valdisplay;
}
public void setValdisplay(String valdisplay) {
this.valdisplay = valdisplay;
}
public UIComponent getValbinding() {
return valbinding;
}
public void setValbinding(UIComponent valbinding) {
this.valbinding = valbinding;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClientname() {
return clientname;
}
public void setClientname(String clientname) {
this.clientname = clientname;
}
public String getFavColor1() {
return favColor1;
}
public void setFavColor1(String favColor1) {
this.favColor1 = favColor1;
}
public void setchangeval(AjaxBehaviorEvent e){
this.setValdisplay("none");
if(this.getFavColor1().equalsIgnoreCase("red")){
this.setValdisplay("block");
this.setMessage("RED");
}else if(this.getFavColor1().equalsIgnoreCase("Green")){
this.setValdisplay("block");
this.setMessage("GREEN");
}
}
public void setDropDwnVal(AjaxBehaviorEvent e){
if(this.getFavoriteCar2().equalsIgnoreCase("116")){
LinkedList<Car> ob = new LinkedList<Car>();
ob.add(new Car("Aife","0"));
ob.add(new Car("Anirban","1"));
this.setCar3List(ob);
}else {
LinkedList<Car> ob1 = new LinkedList<Car>();
ob1.add(new Car("Saife","0"));
ob1.add(new Car("Abid","1"));
this.setCar3List(ob1);
}
}
}
Car.java:
import java.io.Serializable;
public class Car implements Serializable {
public String carlabel;
public String carvalue;
public Car(String carLabel, String carValue) {
this.carlabel=carLabel;
this.carvalue=carValue;
}
public String getCarlabel() {
return carlabel;
}
public void setCarlabel(String carlabel) {
this.carlabel = carlabel;
}
public String getCarvalue() {
return carvalue;
}
public void setCarvalue(String carvalue) {
this.carvalue = carvalue;
}
}
The second dropdown down is not coming properly.In listener method of first dropdown the value from first drop down is not 116/118/120.
***The dbms portion is to be ignored.I had put it for another implementation.
I was able to spot several problems.
You closed your h:form just after the group of radio buttons, but continued to put other elements outside the form. Similarly, your f:view is closed right after the panel group, yet other form elements appear after this one. Just move the closing tags for your h:form and f:view right after closing tag of the last h:selectOneMenu (in this order), this should fix one part of your problem.
Both of your f:ajax are bound to click, change this to change, otherwise actions are performed even when user, for example, just opens the dropdown.
Both of your f:ajax have render defined as something starting with colon - I had to remove the colon, otherwise the elements were not found.
The "Choose your owner" dropdown's value is bound to an empty string, which is not correct. Change this to value="#{authorData.favoriteCar2}".
The method Author.getCar4List() creates a new list each time it is called. Consider keeping only return car4List; there and moving the creation to a separate method, annotated with #PostConstruct so that it is only called once:
#PostConstruct
private void init() {
car4List = new ArrayList<Car>();
car4List.add(new Car("BMW", "116"));
car4List.add(new Car("AUDI", "118"));
car4List.add(new Car("MERCEDES", "120"));
}
I hope these are all the changes I made, cannot recall there would be anything else needed.
userData definition was not part of the code you shared here, so I had to replace some of these references with authorData and remove few of them, but that should not have much impact to the things mentioned above.
Related
What I doing is just an application where the selected option display in the textArea. But Ajax is not working after lending the page after navigation from the main menu on this page. That function only works after using the submit button.
Below is my JSF page code
<ui:composition 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"
template="/WEB-INF/template.xhtml">
<ui:define name="title">
Ajax Framework - <span class="subitem">Basic</span>
</ui:define>
<ui:define name="description">
This example demonstrates a simple but common usage of posting the form, updating the backend value and displaying the output with ajax.
</ui:define>
<ui:define name="implementation">
<h:form>
<p:panel id="panel" header="Form" style="margin-bottom:10px;">
<p:messages>
<p:autoUpdate />
</p:messages>
<h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
<p:outputLabel for="lazy" value="Lazy:" />
<p:selectOneMenu id="lazy" value="#{selectOneMenuView.option}" lazy="true" style="width:125px">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{selectOneMenuView.options}" />
<f:ajax event="change" listener="#{selectOneMenuView.onChange}" execute="#this" render="textarea1"/>
</p:selectOneMenu>
</h:panelGrid>
<p:commandButton value="Submit" update="display" oncomplete="PF('dlg').show()" icon="ui-icon-check" />
<p:dialog header="Values" modal="true" showEffect="bounce" widgetVar="dlg" resizable="false">
<p:panelGrid columns="2" id="display" columnClasses="label,value">
<h:outputText value="Lazy:" />
<h:outputText value="#{selectOneMenuView.option}" />
</p:panelGrid>
</p:dialog>
<h3>AutoResize</h3>
<p:inputTextarea id="textarea1" value="#{selectOneMenuView.inputTextArea}" rows="6" cols="33" />
</p:panel>
</h:form>
</ui:define>
</ui:composition>
And my managed bean is as below
package org.primefaces.showcase.view.input;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.model.SelectItem;
import javax.faces.model.SelectItemGroup;
import org.primefaces.showcase.domain.Theme;
import org.primefaces.showcase.service.ThemeService;
#ManagedBean
public class SelectOneMenuView {
private String console;
private String car;
private List<SelectItem> cars;
private String city;
private Map<String,String> cities = new HashMap<String, String>();
private Theme theme;
private List<Theme> themes;
private String option;
private List<String> options;
private String inputTextArea;
public String getInputTextArea() {
return inputTextArea;
}
public void setInputTextArea(String inputTextArea) {
this.inputTextArea = inputTextArea;
}
#ManagedProperty("#{themeService}")
private ThemeService service;
#PostConstruct
public void init() {
//cars
SelectItemGroup g1 = new SelectItemGroup("German Cars");
g1.setSelectItems(new SelectItem[] {new SelectItem("BMW", "BMW"), new SelectItem("Mercedes", "Mercedes"), new SelectItem("Volkswagen", "Volkswagen")});
SelectItemGroup g2 = new SelectItemGroup("American Cars");
g2.setSelectItems(new SelectItem[] {new SelectItem("Chrysler", "Chrysler"), new SelectItem("GM", "GM"), new SelectItem("Ford", "Ford")});
cars = new ArrayList<SelectItem>();
cars.add(g1);
cars.add(g2);
//cities
cities = new HashMap<String, String>();
cities.put("New York", "New York");
cities.put("London","London");
cities.put("Paris","Paris");
cities.put("Barcelona","Barcelona");
cities.put("Istanbul","Istanbul");
cities.put("Berlin","Berlin");
//themes
themes = service.getThemes();
//options
options = new ArrayList<String>();
for(int i = 0; i < 20; i++) {
options.add("Option " + i);
}
}
public String getConsole() {
return console;
}
public void setConsole(String console) {
this.console = console;
}
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Theme getTheme() {
return theme;
}
public void setTheme(Theme theme) {
this.theme = theme;
}
public List<SelectItem> getCars() {
return cars;
}
public Map<String, String> getCities() {
return cities;
}
public List<Theme> getThemes() {
return themes;
}
public void setService(ThemeService service) {
this.service = service;
}
public String getOption() {
return option;
}
public void setOption(String option) {
this.option = option;
}
public List<String> getOptions() {
return options;
}
public void setOptions(List<String> options) {
this.options = options;
}
public void onChange(){
this.inputTextArea = this.option;
}
}
May I know why? Can anyone give me some guideline?
This question already has answers here:
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
(12 answers)
Closed 6 years ago.
I'm new to JSF.I followed a tutorial of JSF step by step but I'm unable to get the data from ManagedBean to xhtml page when I run it.Below are each class I have created.
UserData.java
package com.practise.test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "userData", eager = true)
#SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String dept;
private int age;
private double salary;
private static final ArrayList<Employee> employees
= new ArrayList<Employee>(Arrays.asList(
new Employee("John", "Marketing", 30,2000.00),
new Employee("Robert", "Marketing", 35,3000.00),
new Employee("Mark", "Sales", 25,2500.00),
new Employee("Chris", "Marketing", 33,2500.00),
new Employee("Peter", "Customer Care", 20,1500.00)
));
public ArrayList<Employee> getEmployees() {
return employees;
}
public String addEmployee() {
Employee employee = new Employee(name,dept,age,salary);
employees.add(employee);
return null;
}
public String deleteEmployee(Employee employee) {
employees.remove(employee);
return null;
}
public String editEmployee(Employee employee){
employee.setCanEdit(true);
return null;
}
public String saveEmployees(){
//set "canEdit" of all employees to false
for (Employee employee : employees){
employee.setCanEdit(false);
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return dept;
}
public void setDepartment(String department) {
this.dept = department;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
Employee.java
package com.practise.test;
public class Employee {
private String name;
private String department;
private int age;
private double salary;
private boolean canEdit;
public Employee (String name,String department,int age,double salary){
this.name = name;
this.department = department;
this.age = age;
this.salary = salary;
canEdit = false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public boolean isCanEdit() {
return canEdit;
}
public void setCanEdit(boolean canEdit) {
this.canEdit = canEdit;
}
}
home.xhtml
<?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="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>JSF tutorial</title>
<h:outputStylesheet library="css" name="styles.css" />
</h:head>
<h:body>
<h2>DataTable Example</h2>
<h:form>
<h:dataTable value="#{userData.employees}" var="employee"
styleClass="employeeTable"
headerClass="employeeTableHeader"
rowClasses="employeeTableOddRow,employeeTableEvenRow">
<h:column>
<f:facet name="header">Name</f:facet>
#{employee.name}
</h:column>
<h:column>
<f:facet name="header">Department</f:facet>
#{employee.department}
</h:column>
<h:column>
<f:facet name="header">Age</f:facet>
#{employee.age}
</h:column>
<h:column>
<f:facet name="header">Salary</f:facet>
#{employee.salary}
</h:column>
</h:dataTable>
<h3>Add Employee</h3>
<hr/>
<table>
<tr>
<td>Name :</td>
<td><h:inputText size="10" value="#{userData.name}" /></td>
</tr>
<tr>
<td>Department :</td>
<td><h:inputText size="20" value="#{userData.dept}" /></td>
</tr>
<tr>
<td>Age :</td>
<td><h:inputText size="5" value="#{userData.age}" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><h:inputText size="5" value="#{userData.salary}" /></td>
</tr>
<tr>
<td> </td>
<td><h:commandButton value="Add Employee"
action="#{userData.addEmployee}" /></td>
</tr>
</table>
</h:form>
</h:body>
</html>
Can someone help me out to figure out what is the exact issue and how to overcome it.Thanks in advance.
Because you have userData.dept, expression language will look for getDept()/setDept() methods which u don't have. which will throw an error. You need use the proper naming.
Change
<h:inputText size="20" value="#{userData.dept}" />
To
<h:inputText size="20" value="#{userData.department}" />
I have the datatable inside the rowExpansion and I can select rows of that table by means of checkboxes. I select some of them. But after I click on the row-toggler icon to untoggle inner table the event resets checkboxes in "false".
Can I avoid this behavior ?
Car Brand:
import java.util.List;
public class CarBrand {
private final String brandName;
private final List<CarModel> models;
private boolean selected;
public CarBrand(String brandName, List<CarModel> models) {
this.brandName = brandName;
this.models = models;
}
public String getBrandName() {
return brandName;
}
public List<CarModel> getModels() {
return models;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
Car Model:
public class CarModel {
private final String modelName;
private final int year;
private boolean selected;
public CarModel(String modelName, int year) {
this.modelName = modelName;
this.year = year;
}
public String getModelName() {
return modelName;
}
public int getYear() {
return year;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
CDI Managed Bean:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.inject.Named;
import org.primefaces.event.ToggleEvent;
import org.primefaces.model.Visibility;
#Named
#SessionScoped
public class Bean implements Serializable {
List<CarBrand> brands;
#PostConstruct
private void init() {
brands = new ArrayList<>();
List<CarModel> carModels;
carModels = new ArrayList<>();
carModels.add(new CarModel("CL 63 AMG", 2011, 1));
carModels.add(new CarModel("S-Class Coupe", 2014, 2));
carModels.add(new CarModel("AMG GTS", 2015, 3));
brands.add(new CarBrand("Mercedes", carModels));
carModels = new ArrayList<>();
carModels.add(new CarModel("M5 F10", 2012, 4));
carModels.add(new CarModel("M6 F13", 2012, 5));
carModels.add(new CarModel("X5 M", 2015, 6));
brands.add(new CarBrand("BMW", carModels));
carModels = new ArrayList<>();
carModels.add(new CarModel("Polo", 2012, 7));
carModels.add(new CarModel("Golf GTI", 2013, 8));
carModels.add(new CarModel("Golf R", 2015, 9));
brands.add(new CarBrand("Volkswagen", carModels));
}
public void onRowToggle(AjaxBehaviorEvent event) {
ToggleEvent toggleEvent = (ToggleEvent) event;
FacesMessage msg;
if (toggleEvent.getVisibility() == Visibility.VISIBLE) {
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Toggled", "Visibility:" + toggleEvent.getVisibility());
} else {
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Untoggled", "Visibility:" + toggleEvent.getVisibility());
}
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public List<CarBrand> getBrands() {
return brands;
}
}
and .xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<f:view>
<h:head>
<title>TEST</title>
</h:head>
<h:body>
<h:form id="testForm" prependId="true">
<p:growl id="growl"/>
<p:dataTable id="carsTable" value="#{bean.brands}" var="brand" style="width: 400px">
<p:ajax event="rowToggle" listener="#{bean.onRowToggle}" update="testForm:growl"/>
<p:column style="width: 20px">
<p:rowToggler/>
</p:column>
<p:column headerText="Brand">
<b><h:outputText value="#{brand.brandName}"/></b>
</p:column>
<p:rowExpansion>
<p:dataTable id="modelsTable" value="#{brand.models}" var="model">
<p:column headerText="Model">
<h:outputText value="#{model.modelName}"/>
</p:column>
<p:column headerText="Year">
<h:outputText value="#{model.year}"/>
</p:column>
<p:column style="width: 20px">
<f:facet name="header">
<p:selectBooleanCheckbox id="selectAll" value="#{brand.selected}" rendered="#{not empty brand.models}">
<p:ajax/>
</p:selectBooleanCheckbox>
</f:facet>
<p:selectBooleanCheckbox id="modelSelect" value="#{model.selected}">
<p:ajax/>
</p:selectBooleanCheckbox>
</p:column>
</p:dataTable>
</p:rowExpansion>
</p:dataTable>
</h:form>
</h:body>
</f:view>
The problem is even worse than you mention. It is caused by the implementation of the toggle. If you see what is going on in the DOM, the expanded items get removed completely. When you toggle it back, the object are re-rendered.
For some reason text values are preserved, but the checkboxes get reverted to their original value.
The situation is worth though. If you do not expand the expansion, then the not rendered elements are not submitted, which for checkboxes means their values are changed to "false" no matter what was their original value.
You have basically two options:
move checkboxes outside the expansion
store their value using Javascript outside their expanded area
This question already has answers here:
How to populate options of h:selectOneMenu from database?
(5 answers)
Closed 8 years ago.
I am new in JSF and facing problem in getting the drop down list. I don't want to use the #PostConstructor. I tried couple of sources on google but i don't know where i am making the mistake. please hep me out.
Managed Bean
package com.employee.registration;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class EmployeeBean implements Serializable {
private static final long serialVersionUID = -5400118477202860998L;
private String firstName;
private String lastName;
private String emailID;
private int employeeNumber;
private String employeeDepartment;
private String dplist;
private List<DepartmentList> departmentList;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailID() {
return emailID;
}
public void setEmailID(String emailID) {
this.emailID = emailID;
}
public int getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeDepartment() {
return employeeDepartment;
}
public void setEmployeeDepartment(String employeeDepartment) {
this.employeeDepartment = employeeDepartment;
}
public List<DepartmentList> getDepartmentList() {
return departmentList;
}
public void setDepartmentList(List<DepartmentList> departmentList) {
this.departmentList = departmentList;
}
public List<DepartmentList> getDepartments() {
departmentList = new ArrayList<DepartmentList>();
departmentList.add(new DepartmentList("1", "Finance"));
departmentList.add(new DepartmentList("2", "Bnking"));
return departmentList;
}
public String getDplist() {
return dplist;
}
public void setDplist(String dplist) {
this.dplist = dplist;
}
}
Java Class
package com.employee.registration;
public class DepartmentList {
private String departmentId;
private String departmentName;
public DepartmentList(String departmentId, String departmentName) {
this.departmentId = departmentId;
this.departmentName = departmentName;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
XHTML
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Employee Registration</title>
<h:outputStylesheet library="css" name="stylesheet.css" />
</h:head>
<h:body>
<h:form>
<fieldset>
<legend>Enter the Employees Information </legend>
<h:outputLabel id="firstName" value="First Name :" for="fName"></h:outputLabel>
<h:inputText id="fName" value="#{employeeBean.firstName}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="lastName" value="Last Name :" for="lName"></h:outputLabel>
<h:inputText id="lName" value="#{employeeBean.lastName}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="emailId" value="Email ID :"></h:outputLabel>
<h:inputText id="email" value="#{employeeBean.emailID}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="employeeNumberId" value="Employee Number :"></h:outputLabel>
<h:inputText id="empNumber" value="#{employeeBean.employeeNumber}"></h:inputText>
<br></br>
<h:outputLabel id="employeeDepartmentID" value="Employee Department"></h:outputLabel>
<h:inputText id="eDepartment"
value="#{employeeBean.employeeDepartment}"></h:inputText>
<br></br>
<h:selectOneMenu value="#{employeeBean.dplist}"></h:selectOneMenu>
<f:selectItems value="#{employeeBean.departmentList}" var="e"
itemLabel="#{e.departmentId}" itemValue="#{e.departmentName}"></f:selectItems>
<h:commandButton id="submit" value="Submit"
action="outputInformation"></h:commandButton>
</fieldset>
</h:form>
</h:body>
</html>
selectItems tag should be inside selectOneMenu :)
<h:selectOneMenu value="#{employeeBean.dplist}}">
<f:selectItems value="#{employeeBean.departmentList}" var="e"
itemLabel="#{e.departmentId}" itemValue="#{e.departmentName}" />
</h:selectOneMenu>
see tutorial here
I have using primefaces in my project. I need to create and delete field dynamically on my project. Here I am going to attached my code please find it
my xhtml page is
<ui:composition 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:panelGrid border="0" columns="3" cellpadding="4" columnClasses="control-label">
<h:panelGrid columns="3" cellpadding="4" >
<h:outputText value="Individual Email"/>
<div>
<h:dataTable value="#{utilBean.attachments}" var="attachmentBean" binding="#{utilBean.data}" id="attachments">
<h:column>
<h:inputText id="attachment" value="#{attachmentBean.emailAddress}" binding="#{utilBean.attachment}"/>
</h:column>
<h:column>
<h:commandButton id="delete" value="Delete" immediate="true" actionListener="#{utilBean.deleteAddress}"/>
</h:column>
</h:dataTable>
<h:commandButton id="add" value="Add Email Address" immediate="true" actionListener="#{utilBean.addAddress}" />
</div>
<br/>
</h:panelGrid>
</h:panelGrid>
</ui:composition>
My Bean Is:
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIData;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
#ManagedBean
#SessionScoped
public class UtilBean{
private UIData data=null;
private UIInput attachment = null;
private List<AttachmentBean> attachments = new ArrayList<AttachmentBean>();
public void addAddress(ActionEvent event){
attachments.add(new AttachmentBean());
this.updateAddresses();
FacesContext.getCurrentInstance().renderResponse();
System.out.println("adress size:" + attachments.size());
}
public void deleteAddress(ActionEvent event){
int index = data.getRowIndex();
this.updateAddresses();
this.getAttachments().remove(index);
FacesContext.getCurrentInstance().renderResponse();
}
public void updateAddresses(){
System.out.println("adress sizedfdfdfdf:" + attachments.size());
#SuppressWarnings("unchecked")
List<AttachmentBean> list = (ArrayList<AttachmentBean>)data.getValue();
for(int i =0;i<data.getRowCount();i++){
data.setRowIndex(i);
list.get(i).setEmailAddress((String)getAttachment().getSubmittedValue());
}
data.setRowIndex(0);
}
public UIData getData() {
return data;
}
public void setData(UIData data) {
this.data = data;
}
public UIInput getAttachment() {
return attachment;
}
public void setAttachment(UIInput attachment) {
this.attachment = attachment;
}
public List<AttachmentBean> getAttachments() {
return attachments;
}
public void setAttachments(List<AttachmentBean> attachments) {
this.attachments = attachments;
}
}
And the Attachment Class is
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
#ManagedBean
#SessionScoped
public class AttachmentBean implements Serializable {
private static final long serialVersionUID = 1L;
private String emailAddress;
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public AttachmentBean() {
super();
}
}
I am not able to add textBox by clicking the add button. Please help. Thanks in advance.
You need to put the whole in a <h:form>. See also commandButton/commandLink/ajax action/listener method not invoked or input value not updated.
Another major mistake is here:
<h:dataTable ... binding="#{utilBean.data}">
...
<h:inputText ... binding="#{utilBean.attachment}"/>
Remove those binding attributes. UI components are request scoped and yet you're binding them to a session scoped bean. This would fail hard if you open the same page in multiple browser windows in the same session. See also How does the 'binding' attribute work in JSF? When and how should it be used?.
That said, the #ManagedBean #SessionScoped on AttachmentBean is completely unnecessary. Get rid of those annotations. The #SessionScoped on UtilBean is also rather strange. The #ViewScoped is much better at its place here. See also How to choose the right bean scope?