h:SelectOneMenu onchange event not working - jsf-2

i have two oneSelectMenu loaded with default values based on login Details,then second selectonemenu should load value based on first selectonemenu's onchangeEvent menu.i tried to clear the default value before onchange event but the value remains and doesn't work with onchange event.
<h:selectOneMenu id="blS" value="#{BoardAction.serviceAreaId}" >
<f:ajax event="valueChange" render="blSearchFacilityInput" listener="#{BoardAction.svaValueChangeEvent}"/>
<f:selectItems value="#{BoardAction.serviceAreaList}" var="c" itemLabel="#{c.svaCode}" itemValue="#{c.id}"/> </h:selectOneMenu>
<h:selectOneMenu id="blSearchFacilityInput" value="#{BoardAction.facilityId}"> <f:ajax event="valueChange" render="blSearchSectorInput" listener="#{BoardAction.facValueChangeEvent}"/>
<f:selectItems value="#{BoardAction.svaFaciltyList}" var="c" itemLabel="#{c.facCode}" itemValue="#{c.id}"/></h:selectOneMenu>
ActionBean :
private List<FacilityEBean> svaFaciltyList=null;
public List<FacilityEBean> getSvaFaciltyList() {
svaFaciltyList = facilityBusServ.getFacilityListBySVAId(session.getLoginUser());
return svaFaciltyList;
}
public List<FacilityEBean> svaValueChangeEvent(){
if(svaFaciltyList!=null){
svaFaciltyList.clear();
svaFaciltyList=null;
}
svaFaciltyList = facilityBusServ.getFacilityList(Integer.parseInt(serviceAreaId));
return svaFaciltyList;
}

Your code logic flow is wrong. You seem to expect that input components are in some way directly bound to properties and that the ajax action listener methods can return (changed) property values. This is thus actually not true.
For example, the EL expression #{BoardAction.serviceAreaList} actually invokes the getter method for the property. In your particular case, the getter method fills the list with the results from the DB everytime. So whatever you're setting in the ajax listener method is overridden everytime by the business logic in the getter method.
Those getter methods should not contain business logic at all. You need to rewrite your code as follows:
private List<FacilityEBean> svaFaciltyList;
#PostConstruct
public void init() {
svaFaciltyList = facilityBusServ.getFacilityListBySVAId(session.getLoginUser());
}
public void svaValueChangeEvent() {
svaFaciltyList = facilityBusServ.getFacilityList(Integer.parseInt(serviceAreaId));
}
public List<FacilityEBean> getSvaFaciltyList() {
return svaFaciltyList;
}

Related

JSF SelectOneMenu value cannot be user defined type? [duplicate]

I am creating a web application, where you have to read a list of objects / entities from a DB and populate it in a JSF <h:selectOneMenu>. I am unable to code this. Can someone show me how to do it?
I know how to get a List<User> from the DB. What I need to know is, how to populate this list in a <h:selectOneMenu>.
<h:selectOneMenu value="#{bean.name}">
...?
</h:selectOneMenu>
Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem instances. This is fortunately not needed anymore in JSF 2.x.
Basic example
To answer your question directly, just use <f:selectItems> whose value points to a List<T> property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T actually represents a String.
<h:selectOneMenu value="#{bean.name}">
<f:selectItems value="#{bean.names}" />
</h:selectOneMenu>
with
#ManagedBean
#RequestScoped
public class Bean {
private String name;
private List<String> names;
#EJB
private NameService nameService;
#PostConstruct
public void init() {
names = nameService.list();
}
// ... (getters, setters, etc)
}
Simple as that. Actually, the T's toString() will be used to represent both the dropdown item label and value. So, when you're instead of List<String> using a list of complex objects like List<SomeEntity> and you haven't overridden the class' toString() method, then you would see com.example.SomeEntity#hashcode as item values. See next section how to solve it properly.
Also note that the bean for <f:selectItems> value does not necessarily need to be the same bean as the bean for <h:selectOneMenu> value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.
<h:selectOneMenu value="#{bean.name}">
<f:selectItems value="#{data.names}" />
</h:selectOneMenu>
Complex objects as available items
Whenever T concerns a complex object (a javabean), such as User which has a String property of name, then you could use the var attribute to get hold of the iteration variable which you in turn can use in itemValue and/or itemLabel attribtues (if you omit the itemLabel, then the label becomes the same as the value).
Example #1:
<h:selectOneMenu value="#{bean.userName}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>
with
private String userName;
private List<User> users;
#EJB
private UserService userService;
#PostConstruct
public void init() {
users = userService.list();
}
// ... (getters, setters, etc)
Or when it has a Long property id which you would rather like to set as item value:
Example #2:
<h:selectOneMenu value="#{bean.userId}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>
with
private Long userId;
private List<User> users;
// ... (the same as in previous bean example)
Complex object as selected item
Whenever you would like to set it to a T property in the bean as well and T represents an User, then you would need to bake a custom Converter which converts between User and an unique string representation (which can be the id property). Do note that the itemValue must represent the complex object itself, exactly the type which needs to be set as selection component's value.
<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>
with
private User user;
private List<User> users;
// ... (the same as in previous bean example)
and
#ManagedBean
#RequestScoped
public class UserConverter implements Converter {
#EJB
private UserService userService;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return userService.find(Long.valueOf(submittedValue));
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (modelValue instanceof User) {
return String.valueOf(((User) modelValue).getId());
} else {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
}
}
}
(please note that the Converter is a bit hacky in order to be able to inject an #EJB in a JSF converter; normally one would have annotated it as #FacesConverter(forClass=User.class), but that unfortunately doesn't allow #EJB injections)
Don't forget to make sure that the complex object class has equals() and hashCode() properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.
public class User {
private Long id;
#Override
public boolean equals(Object other) {
return (other != null && getClass() == other.getClass() && id != null)
? id.equals(((User) other).id)
: (other == this);
}
#Override
public int hashCode() {
return (id != null)
? (getClass().hashCode() + id.hashCode())
: super.hashCode();
}
}
Complex objects with a generic converter
Head to this answer: Implement converters for entities with Java Generics.
Complex objects without a custom converter
The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu> without the need to create a custom converter. The SelectItemsConverter will simply do the conversion based on readily available items in <f:selectItem(s)>.
<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>
See also:
Our <h:selectOneMenu> wiki page
View-Page
<h:selectOneMenu id="selectOneCB" value="#{page.selectedName}">
<f:selectItems value="#{page.names}"/>
</h:selectOneMenu>
Backing-Bean
List<SelectItem> names = new ArrayList<SelectItem>();
//-- Populate list from database
names.add(new SelectItem(valueObject,"label"));
//-- setter/getter accessor methods for list
To display particular selected record, it must be one of the values in the list.
Roll-your-own generic converter for complex objects as selected item
The Balusc gives a very useful overview answer on this subject. But there is one alternative he does not present: The Roll-your-own generic converter that handles complex objects as the selected item. This is very complex to do if you want to handle all cases, but pretty simple for simple cases.
The code below contains an example of such a converter. It works in the same spirit as the OmniFaces SelectItemsConverter as it looks through the children of a component for UISelectItem(s) containing objects. The difference is that it only handles bindings to either simple collections of entity objects, or to strings. It does not handle item groups, collections of SelectItems, arrays and probably a lot of other things.
The entities that the component binds to must implement the IdObject interface. (This could be solved in other way, such as using toString.)
Note that the entities must implement equals in such a way that two entities with the same ID compares equal.
The only thing that you need to do to use it is to specify it as converter on the select component, bind to an entity property and a list of possible entities:
<h:selectOneMenu value="#{bean.user}" converter="selectListConverter">
<f:selectItem itemValue="unselected" itemLabel="Select user..."/>
<f:selectItem itemValue="empty" itemLabel="No user"/>
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>
Converter:
/**
* A converter for select components (those that have select items as children).
*
* It convertes the selected value string into one of its element entities, thus allowing
* binding to complex objects.
*
* It only handles simple uses of select components, in which the value is a simple list of
* entities. No ItemGroups, arrays or other kinds of values.
*
* Items it binds to can be strings or implementations of the {#link IdObject} interface.
*/
#FacesConverter("selectListConverter")
public class SelectListConverter implements Converter {
public static interface IdObject {
public String getDisplayId();
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.isEmpty()) {
return null;
}
return component.getChildren().stream()
.flatMap(child -> getEntriesOfItem(child))
.filter(o -> value.equals(o instanceof IdObject ? ((IdObject) o).getDisplayId() : o))
.findAny().orElse(null);
}
/**
* Gets the values stored in a {#link UISelectItem} or a {#link UISelectItems}.
* For other components returns an empty stream.
*/
private Stream<?> getEntriesOfItem(UIComponent child) {
if (child instanceof UISelectItem) {
UISelectItem item = (UISelectItem) child;
if (!item.isNoSelectionOption()) {
return Stream.of(item.getValue());
}
} else if (child instanceof UISelectItems) {
Object value = ((UISelectItems) child).getValue();
if (value instanceof Collection) {
return ((Collection<?>) value).stream();
} else {
throw new IllegalStateException("Unsupported value of UISelectItems: " + value);
}
}
return Stream.empty();
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) return null;
if (value instanceof String) return (String) value;
if (value instanceof IdObject) return ((IdObject) value).getDisplayId();
throw new IllegalArgumentException("Unexpected value type");
}
}
I'm doing it like this:
Models are ViewScoped
converter:
#Named
#ViewScoped
public class ViewScopedFacesConverter implements Converter, Serializable
{
private static final long serialVersionUID = 1L;
private Map<String, Object> converterMap;
#PostConstruct
void postConstruct(){
converterMap = new HashMap<>();
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object object) {
String selectItemValue = String.valueOf( object.hashCode() );
converterMap.put( selectItemValue, object );
return selectItemValue;
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String selectItemValue){
return converterMap.get(selectItemValue);
}
}
and bind to component with:
<f:converter binding="#{viewScopedFacesConverter}" />
If you will use entity id rather than hashCode you can hit a collision- if you have few lists on one page for different entities (classes) with the same id
Call me lazy but coding a Converter seems like a lot of unnecessary work. I'm using Primefaces and, not having used a plain vanilla JSF2 listbox or dropdown menu before, I just assumed (being lazy) that the widget could handle complex objects, i.e. pass the selected object as is to its corresponding getter/setter like so many other widgets do. I was disappointed to find (after hours of head scratching) that this capability does not exist for this widget type without a Converter. In fact if you supply a setter for the complex object rather than for a String, it fails silently (simply doesn't call the setter, no Exception, no JS error), and I spent a ton of time going through BalusC's excellent troubleshooting tool to find the cause, to no avail since none of those suggestions applied. My conclusion: listbox/menu widget needs adapting that other JSF2 widgets do not. This seems misleading and prone to leading the uninformed developer like myself down a rabbit hole.
In the end I resisted coding a Converter and found through trial and error that if you set the widget value to a complex object, e.g.:
<p:selectOneListbox id="adminEvents" value="#{testBean.selectedEvent}">
... when the user selects an item, the widget can call a String setter for that object, e.g. setSelectedThing(String thingString) {...}, and the String passed is a JSON String representing the Thing object. I can parse it to determine which object was selected. This feels a little like a hack, but less of a hack than a Converter.

How do I know which EL expression is triggering particular bean method?

There is a bean method which provides data for a number of xthml tags on a page. For debugging purposes I'd like to know which node in a ViewRoot is triggering the method. Something like that:
<ui:repeat id="alpha" value="#{myBean.objectList}" var="obj">
<!-- some stuff here -->
</ui:repeat>
and the method itself:
public List getObjectList() {
String id = ????;
logger.info("I'm being called by:" + id); // returning "alpha", "beta"
// or whatever component
// calling this method
}
Is it possible?
You can use UIComponent#getCurrentComponent() to obtain the UI component instance currently being processed in the JSF lifecycle.
UIComponent currentComponent = UIComponent.getCurrentComponent(FacesContext.getCurrentInstance());
String currentComponentId = currentComponent.getId();
// ...

Generate unique ID in inputText on page load

I want to genrate a unique number in <p:inputText> on page load.
I can generate an unique value using java.util.UUID, but how can I set it on the value of the <p:inputText> on page load?
<p:inputText id="ptId" label="PatientId" value="#{addBB.pt.patientId}" />
Just set the value during bean's (post)construction.
#ManagedBean
#ViewScoped
public class AddBB {
private Patient pt;
#PostConstruct
public void init() {
pt = new Patient();
pt.setPatientId(UUID.randomUUID().toString());
}
// ...
}
you can do this just by making userId, the default value for inputText like this -
value="#{beanName.userId}"
so that first use it like u want to use and then u can set the value of userId at any point of time as the unique id, just remember to reRender it.
Hope you got what u wanted....

Binding primefaces dataTable with org.primefaces.component.datatable.DataTable;

I have a question regarding primefaces datatable component. I want to bind a DataTable variable to the p:dataTable so that I would be able to manipulate the first, rows, rowsPerPageTemplate, etc. programmatically from the backing bean. But I'm stuck and keep getting java.lang.String cannot be cast to javax.faces.component.UIComponent.
Here's my p:dataTable declaration.
<p:dataTable id="dtProductCategoryList" value="#{saProductCategoryController.saproductcategories}" rowsPerPageTemplate="#{appConfig.rowsPerPageTemplate}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
currentPageReportTemplate="{currentPage} #{bundle.DataTablePageSeparator} {totalPages}"
paginatorAlwaysVisible="false" var="item" paginator="true" rows="#{appConfig.rowsPerPageDefault}"
binding="saProductCategoryController.dtProductCategory">
And here's my ViewScoped backing bean.
private DataTable dtProductCategory;
/** Creates a new instance of saProductCategoryController */
public SaProductCategoryController() {
}
#PostConstruct
public void Init() {
try {
dtProductCategory = new DataTable();
//dtProductCategory.
saproductcategories = saProductCategoryFacade.selectAll();
LogController.log.info("Creating postconstruct for saProductCategoryController");
} catch (Exception ex) {
LogController.log.fatal(ex.toString());
}
}
What could be the problem? It seems that the DataTable variable is mistaken for a String?
Appreciate all your help. Thanks.
java.lang.String cannot be cast to javax.faces.component.UIComponent.
The binding attribute must refer an UIComponent, not a plain vanilla String. And indeed, you forgot the #{} around the attribute value which would make it to be treated as a plain vanilla String.
Fix it accordingly:
binding="#{saProductCategoryController.dtProductCategory}"
Replace
binding="saProductCategoryController.dtProductCategory"
with
binding="#{saProductCategoryController.dtProductCategory}"

JSF 2 custom component with h:commandLink inside ui:repeat

I developed a custom component (inspired by this article by BalusC) that contains a ui:repeat tag displaying the list of clickable table pages.
Inside the loop block there is a h:commandLink that calls asynchronously an action, posting a parameter. The parameter value changes at every loop. Here's the page code:
[...]
<ui:repeat value="#{cc.attrs.pager.pages}" var="loopPage">
<li>
<h:commandLink
action="#{cc.attrs.pager.changePage}"
value="#{loopPage}"
rendered="#{loopPage != cc.attrs.pager.currentPage}"
immediate="true"
>
<f:param name="selectedPage" value="#{loopPage}" />
<f:ajax execute="#this" render="#{cc.attrs.render}" />
</h:commandLink>
<h:outputText
value="#{loopPage}"
rendered="#{loopPage == cc.attrs.pager.currentPage}"
/>
</li>
</ui:repeat>
[...]
Now, the cc.attrs.pager component attribute is noting else that the view-scoped backing bean, whose pages and currentPage attributes are visible through getters, and changePagemethod is the action to call. The cc.attrs.render component attribute is the target to be refreshed after every action execution. Here is the relevant bean code:
[...]
private Integer[] pages;
private int currentPage;
[...]
public Integer[] getPages() {
return pages;
}
public int getCurrentPage() {
return currentPage;
}
[...]
public void changePage() {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance()
.getExternalContext()
.getRequest()
;
String page = request.getParameter("selectedPage");
changePage(Integer.valueOf(page) * rowsPerPage);
}
public void changePage(int firstRow){
this.firstRow = firstRow; //Set the first result to be returned
loadDataList(); // Load requested page.
}
[...]
The initial render is perfect: all the page links are correctly shown and the current page number is not linked, as desired. The problem reveals going to another page: nothing happens.
Although the h:commandLink action is posted with the exact loop parameter value, the response returns always the same page (the first).
Debugging it, I observed that the execution doesn't enter in any of the two changePage methods.
I'm not sure if this issue is related to ui:repeat, but omitting it, I can tell that the same mechanism does work for other purposes.
Any suggestion?
I think you should try replacing <ui:repeat> with <c:forEach>

Resources