Country State City dropdown in jsf - jsf

The city Dropdown populated when the state is selected and State Dropdown populated according Country selection; however, it is not doing this.
Problem is when country selected according country state populated in state dropdwon but after it when i select state from state dropdwon list it does not show populate city dropdwon
actual problem is State value not set in state variable when i select state
Here is the code:
JsfPage
<p:selectOneMenu id="countrydrop" value="#{user.country}" >
<f:ajax id="countryajex" listener="#{user.statesbycontry()}" render="statedrop"/>
<f:selectItem itemLabel="Select Country" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{user.allcontry()}" />
</p:selectOneMenu>
<p:selectOneMenu id="statedrop" value="#{user.ustate}" >
<p:ajax event="change" id="stateajex" listener="#{user.citybystate()}" update="citydrop" />
<f:selectItem itemLabel="Select State" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{user.statelist}"/>
</p:selectOneMenu>
<p:selectOneMenu id="citydrop" value="#{user.city}" >
<f:selectItem itemLabel="Select City" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{user.citylist}" />
</p:selectOneMenu>
jsfManagedBean
String country;
String state;
String city;
List<String> statelist;
List<String> citylist;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public List<String> getStatelist() {
return statelist;
}
public void setStatelist(List<String> statelist) {
this.statelist = statelist;
}
public List<String> getCitylist() {
return citylist;
}
public void setCitylist(List<String> citylist) {
this.citylist = citylist;
}
public List<String> allcontry(){
return od_user_bean.allcountries();
}
public void statesbycontry(){
//Method tested Working well
statelist = od_user_bean.findstatesbycontries(country);
}
public void citybystate(){
System.out.println("State="+state);
if(state != null)
//Method tested Working well
citylist=od_user_bean.findcitybystate(state);
}

Related

JSF rendered component not binding with ajax call

I need help to render a component that will in turn make an ajax call after it has been rendered but with no success.
I have the following code which doesn't work. I don't know if I am missing something. Any help is highly appreciated.
<h:selectOneMenu id="gender" value="#{bean.gender}"
class="form-control"
valueChangeListener="#{bean.updateGenderValue}"
onchange="submit()">
<f:selectItems value="#{bean.genders}" var="gender" itemLabel="#
{gender}" itemValue="#{gender}"/>
</h:selectOneMenu>
<h:selectOneMenu value="#{bean.pregnancyStatus}"
class="form-control"
rendered="#{bean.gender eq 'Female'}">
<f:selectItems value="#{bean.options}"
var="pregnancyStatus" itemLabel="#{pregnancyStatus}"
itemValue="#{pregnancyStatus}"/>
<f:ajax listener="#{bean.updatePregancyValue}"
execute="#this" render="#this"/>
</h:selectOneMenu>
public void updateGenderValue(ValueChangeEvent event) throws IOException {
gender = (String) event.getNewValue();
}
public void updatePregancyValue(AjaxBehaviorEvent event) throws IOException {
System.out.println(":( == " + pregnancyStatus);
}
The pregnancyStatus value is never updated at all.
Did you missed the <h:form>? I copied and pasted your code in my project and
my code:
<div style="height:500px">
<h:form>
<h:selectOneMenu id="gender" value="#{bean.gender}"
class="form-control"
valueChangeListener="#{bean.updateGenderValue}"
onchange="submit()">
<f:selectItems value="#{bean.genders}" var="gender" itemLabel="#
{gender}" itemValue="#{gender}"/>
</h:selectOneMenu>
<h:selectOneMenu value="#{bean.pregnancyStatus}"
class="form-control"
rendered="#{bean.gender eq 'Female'}">
<f:selectItems value="#{bean.options}"
var="pregnancyStatus" itemLabel="#{pregnancyStatus}"
itemValue="#{pregnancyStatus}"/>
<f:ajax listener="#{bean.updatePregancyValue}"
execute="#this" render="#this"/>
</h:selectOneMenu>
lets check the console :
:( == 2
:( == 3
Bean:
#ManagedBean(name = "bean")
#ViewScoped
public class Bean {
private String pregnancyStatus;
private List<SelectItem> options;
private List<SelectItem> genders;
private String gender;
#PostConstruct
public void initBean(){
options = new ArrayList<>();
genders = new ArrayList<>();
options.add(new SelectItem("1"));
options.add(new SelectItem("2"));
options.add(new SelectItem("3"));
genders.add(new SelectItem("Male"));
genders.add(new SelectItem("Female"));
genders.add(new SelectItem("third"));
}
public String getPregnancyStatus() {
return pregnancyStatus;
}
public void setPregnancyStatus(String pregnancyStatus) {
this.pregnancyStatus = pregnancyStatus;
}
public void updateGenderValue(ValueChangeEvent event) throws IOException {
gender = (String) event.getNewValue();
}
public void updatePregancyValue(AjaxBehaviorEvent event) throws IOException {
System.out.println(":( == " + pregnancyStatus);
}
}

Listener is not called by selectOneMenu

I have a p:selectOneMenu that changing value should run a listener to update the value of another p:selectOneMenu (Type: state -> city). In addition to the items have the item "All" in the first p:selectOneMenu. When you select any item other than the "All" the listener is not called, but when I select the "All" option.
I also realized that the model will not be updated. That is the value of the first p:selectOneMenu is not set in the entity attribute,
The following codes:
First
<p:selectOneMenu id="pesquisaCategoria" style="width:100%;"
value="#{inscricaoFaces.entity.categoriaSelecionada}"
styleClass="input-block-level" converter="#{categoriaConverter}">
<f:selectItem itemLabel="#{msgs['label.dropdown.todos']}"
noSelectionOption="true" itemValue="#{null}" />
<f:selectItems value="#{categoriaFaces.listarTodasCategorias()}"
var="categoria" itemValue="#{categoria}"
itemLabel="#{categoria.descricao}" />
<p:ajax update="pesquisaAreaAtuacao" event="change"
listener="#{inscricaoFaces.atualizarAreasAtuacao}" />
</p:selectOneMenu>
Second
<p:selectOneMenu id="pesquisaAreaAtuacao" style="width:100%;"
value="#{inscricaoFaces.entity.areaAtuacao}"
styleClass="input-block-level" converter="#{areaAtuacaoConverter}">
<f:selectItem itemLabel="#{msgs['label.dropdown.todos']}"
noSelectionOption="true" itemValue="#{null}" />
<f:selectItems value="#{inscricaoFaces.areasAtuacao}" var="area"
itemValue="#{area}" itemLabel="#{area.descricao}" />
</p:selectOneMenu>
Convert
#ManagedBean
#RequestScoped
public class CategoriaConverter implements Converter, Serializable {
/**
*
*/
private static final long serialVersionUID = -1073909086688882110L;
#EJB
private CategoriaService categoriaService;
#Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if (value != null && value.trim().length() > 0 && !"Todos".equals(value)) {
return categoriaService.consultarPorId(new Categoria(Integer.valueOf(value)));
} else {
return null;
}
}
#Override
public String getAsString(FacesContext fc, UIComponent uic, Object value) {
if(value != null){
return value instanceof Categoria ? String.valueOf(((Categoria) value).getCodigo()) : null;
}else{
return null;
}
}
}

How to enable/disable inputText on rowSelectCheckbox and rowUnselectCheckbox

I need your help in enabling and disabling inputText based on rowSelectCheckbox and rowUnselectCheckbox if the checkbox is ticked or unticked. If it is ticked, then I need to enable the inputText otherwise it should be disabled on page load and on untick. By default the inputText is disabled on the page load. Here is the code for the jsf:
<h:form id="request">
<p:dataTable value="#{dataTableView.employeeList}" id="Employee" var="emp"
selection="#{dataTableView.selectedEmployees}" rowKey="#{emp.id}">
<p:ajax event="rowSelectCheckbox" listener="#{dataTableView.EnableInputText}" />
<p:ajax event="rowUnselectCheckbox" listener="#{dataTableView.EnableInputText}" />
<p:columnGroup type="header">
<p:row>
<p:column/>
<p:column headerText="ID"/>
<p:column headerText="Name"/>
<p:column headerText="Location"/>
<p:column headerText="Remarks"/>
</p:row>
</p:columnGroup>
<p:column selectionMode="multiple" style="width:2%;text-align:center"/>
<p:column headerText="ID">
<h:outputText value="#{emp.id}"/>
</p:column>
<p:column headerText="Name">
<h:outputText value="#{emp.name}"/>
</p:column>
<p:column headerText="Location">
<h:outputText value="#{emp.location}"/>
</p:column>
<p:column headerText="Remarks">
<h:inputText id="inputT1" value="#{emp.remarks}" disabled="#{emp.disable}"/>
</p:column>
</p:dataTable>
</h:form>
And here is the code in the bean:
private List<Student> employeeList = new ArrayList<Student>();
private List<Student> selectedEmployees;
private boolean disable;
#PostConstruct
public void init() {
//add Employees
disable=true;
Student w1 = new Student(111, "AAAA", "ZZZZ", "", disable);
Student w2 = new Student(222, "CCCCC", "ZZZZZ", "OUT", disable);
Student w3 = new Student(222, "BBBBBB", "YYYYYYY", "IN", disable);
employeeList.add(w1);
employeeList.add(w2);
employeeList.add(w3);
}
public void EnableInputText(SelectEvent event) {
for(int i=0;i<=selectedEmployees.size();i++){ //Assuming you have declared as List
for(int j=0;j<=employeeList.size();j++){
if(selectedEmployees.get(i).getId().equals(employeeList.get(j).getId()))
{
employeeList.get(j).setDisable(false);
break;
}
}
}
}
The Student Bean:
public class Student {
private Integer id;
private String name;
private String location;
private String remarks;
private boolean disable;
public Student(Integer id, String name, String location, String remarks, boolean disable){
this.id = id;
this.name = name;
this.location = location;
this.remarks=remarks;
this.disable=disable;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getRemarks() {
return remarks;
}
public void setDisable(boolean disable) {
this.disable = disable;
}
public boolean isDisable() {
return disable;
}
And in the Bean, I am facing difficulties in enabling the inputText for entry if the row is ticked. So could you please help.
Now I got the error :
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 if I tick and checkbox
First thing you are using selectionMode="multiple" it means there will be multiple rows with textField enabled next
instead of this :
<h:inputText value="#{emp.remarks}" disabled="#{empBean.enable}" />
write
<h:inputText value="#{emp.remarks}" disabled="#{emp.enable}" />
means declare one variable enable in the bean itself after that:
for(int i=0;i<=selectedEmployees.size();i++){ //Assuming you have declared as List
for(int j=0;j<=empList.size();j++){
if(selectedEmployees.get(i).getId().equals(empList.get(j).getId()){
empList.get(j).setEnable(false);
}
}
}
before to this you can write one for loop and disable all the textField for list for that will work for rowUnselect

Rendering elements in MyFaces 1.1.1

I am trying to create a simple jsf page where I have a dropdown whose value determines which label to render. Initially all the labels' render is set as false through the backing bean constructor. But I have called submit onchange which sets the respective values to true for the labels. I have set the scope of the backing bean as session so that the value being set does not get removed onchange. However the label does not get rendered onchange. Below is the code snippet for the jsf page:
<h:form>
<h:panelGroup>
<h:outputLabel styleClass="captionOutputField" value="Select Report Type:" />
<h:selectOneMenu id="selectedMenu" onchange="submit()" valueChangeListener="#{ReportHealth.typeSelectDropDownChange}">
<f:selectItem itemLabel="" itemValue="empty" />
<f:selectItem itemLabel="daily" itemValue="daily" />
<f:selectItem itemLabel="weekly" itemValue="weekly" />
<f:selectItem itemLabel="monthly" itemValue="monthly" />
</h:selectOneMenu>
<h:panelGroup rendered="#{ReportHealth.daily}">
<h3>MENU 0</h3>
</h:panelGroup>
<h:panelGroup rendered="#{ReportHealth.weekly}">
<h3>MENU 1</h3>
</h:panelGroup>
<h:panelGroup rendered="#{ReportHealth.monthly}">
<h3>MENU 2</h3>
</h:panelGroup>
Here is the backing bean:
public class ReportHealth implements Serializable{
private static final long serialVersionUID = 1L;
private boolean weekly;
private boolean monthly;
private boolean daily;
private String menuValue;
public ReportHealth() {
weekly = false;
monthly = false;
daily = false;
}
public String getMenuValue() {
return menuValue;
}
public void setMenuValue(String menuValue) {
this.menuValue = menuValue;
}
public boolean isWeekly() {
return weekly;
}
public void setWeekly(boolean weekly) {
this.weekly = weekly;
}
public boolean isMonthly() {
return monthly;
}
public void setMonthly(boolean monthly) {
this.monthly = monthly;
}
public boolean isDaily() {
return daily;
}
public void setDaily(boolean daily) {
this.daily = daily;
}
public void typeSelectDropDownChange(ValueChangeEvent e)
{
String typeSelectVal = e.getNewValue().toString();
if(typeSelectVal!=null && typeSelectVal.equalsIgnoreCase("daily"))
{
setDaily(true);
setWeekly(false);
setMonthly(false);
}
else if(typeSelectVal!=null && typeSelectVal.equalsIgnoreCase("weekly"))
{
setDaily(false);
setWeekly(true);
setMonthly(false);
}
else if(typeSelectVal!=null && typeSelectVal.equalsIgnoreCase("monthly"))
{
setDaily(false);
setWeekly(false);
setMonthly(true);
}
else
{
setDaily(false);
setWeekly(false);
setMonthly(false);
}
}
}
I dont understand why you are using so complicated code for simple task.
Here is what you need
<h:form>
<h:panelGroup>
<h:outputLabel styleClass="captionOutputField" value="Select Report Type:"/>
<h:selectOneMenu id="selectedMenu" value="#{reportHealth.menuValue}">
<f:selectItem itemLabel="" itemValue="empty" />
<f:selectItem itemLabel="daily" itemValue="daily" />
<f:selectItem itemLabel="weekly" itemValue="weekly" />
<f:selectItem itemLabel="monthly" itemValue="monthly" />
<f:ajax render="#form">
</f:ajax>
</h:selectOneMenu>
<h:panelGroup rendered="#{reportHealth.menuValue eq 'daily'}">
<h3>MENU 0</h3>
</h:panelGroup>
<h:panelGroup rendered="#{reportHealth.menuValue eq 'weekly'}">
<h3>MENU 1</h3>
</h:panelGroup>
<h:panelGroup rendered="#{reportHealth.menuValue eq 'monthly'}">
<h3>MENU 2</h3>
</h:panelGroup>
</h:panelGroup>
</h:form>
and Bean will be
#ManagedBean
#ViewScoped
public class ReportHealth implements Serializable{
private static final long serialVersionUID = 1L;
private String menuValue;
public String getMenuValue() {
return menuValue;
}
public void setMenuValue(String menuValue) {
this.menuValue = menuValue;
}
}
I found out what was wrong with my code. Instead of putting the labels in <H3>tags. I needed to put it in <h:outputText> tag.

JSF/Primefaces issue when form field rendering depends on selectOneMenu

Form field rendering is depending on selected item in selectOneMenu.
Page:
<h:body>
<f:view>
<h:form>
<h:panelGrid>
<p:inputText value="#{user.username}"/>
<p:selectOneMenu value="#{user.moreInputs}"
required="true">
<p:ajax event="change"
update="moreInputGrid"/>
<f:selectItem itemLabel="" itemValue=""/>
<f:selectItems value="#{user.selectItems}"/>
</p:selectOneMenu>
</h:panelGrid>
<h:panelGrid id="moreInputGrid">
<p:inputText rendered="#{user.renderMoreInputs}"
value="#{user.name}"/>
</h:panelGrid>
<p:commandButton action="#{user.register}"
value="Register user"/>
</h:form>
</f:view>
</h:body>
Backing bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
#ManagedBean
#ViewScoped
public class User {
private String username;
private MoreInputs moreInputs;
private String name;
public enum MoreInputs {
YES,
NO
}
public boolean isRenderMoreInputs() {
return (moreInputs == MoreInputs.YES);
}
public SelectItem[] getSelectItems() {
SelectItem[] items = new SelectItem[2];
items[0] = new SelectItem(
MoreInputs.YES,
"yes");
items[1] = new SelectItem(
MoreInputs.NO,
"no");
return items;
}
public String register() {
return null;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public MoreInputs getMoreInputs() {
return moreInputs;
}
public void setMoreInputs(MoreInputs moreInputs) {
this.moreInputs = moreInputs;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Issue arrises if the client does page refresh after choosing an item causing form fields to render. Such form fields will not be rendered on page refresh, although they should. Plus, if client then tries to submit form, validation is skipped for those hidden fields and form is successfully processed.
Am I doing something wrong? Is there an elegant solution?

Resources