<h:selectOneMenu> default value with id from other list [duplicate] - jsf

Is it possible to preselect one of the options from the select menu?
I have this UI Component:
<h:selectOneMenu value="#{authenticateController.country}">
<f:selectItems value="#{constants.countrySelectMenu}" />
</h:selectOneMenu>
The values of #{constants.countrySelectMenu} are a list of country ID - country name pairs.
Is there a way to render the list with a preselected value or at least is there a work-around to get this done?

Just preset the property behind <h:selectOneMenu value> with the desired value. You can do it in for example the bean's (post)constructor, action(listener) method, etc.
In your specific example, thus e.g.
public class AuthenticateController {
private String country;
#PostConstruct
public void init() {
country = "NL";
}
// ...
}
It works exactly the same way for all other UIInput components like <h:inputText> and so on. The input component's value itself simply represents the (pre)selected/checked/filled value.
See also:
How to populate options of h:selectOneMenu from database?

Related

How to set default value and label together for SelectOneMenu? [duplicate]

Is it possible to preselect one of the options from the select menu?
I have this UI Component:
<h:selectOneMenu value="#{authenticateController.country}">
<f:selectItems value="#{constants.countrySelectMenu}" />
</h:selectOneMenu>
The values of #{constants.countrySelectMenu} are a list of country ID - country name pairs.
Is there a way to render the list with a preselected value or at least is there a work-around to get this done?
Just preset the property behind <h:selectOneMenu value> with the desired value. You can do it in for example the bean's (post)constructor, action(listener) method, etc.
In your specific example, thus e.g.
public class AuthenticateController {
private String country;
#PostConstruct
public void init() {
country = "NL";
}
// ...
}
It works exactly the same way for all other UIInput components like <h:inputText> and so on. The input component's value itself simply represents the (pre)selected/checked/filled value.
See also:
How to populate options of h:selectOneMenu from database?

PrimeFaces p:autoComplete not converting in ArrayList

I'm converting from RichFaces to PrimeFaces 11.0 and replacing a custom component based on the old rich:suggestionBox with p:autoComplete. This works perfectly in most code where the value refers to a POJO property. However I'm finding difficulty getting p:autoComplete to set the value of a reference from an ArrayList of POJOs.
class OrderItem {
...
public List<Contact> getContacts() {
return contacts;
}
...
}
On a view, we want to be able to allow autoCompletes on multiple contacts per orderItem. The orderItem.contacts list is prepopulated with null placeholders by the time this is rendered:
<ui:repeat id="assignabilityContacts" value="#{orderItem.contacts}" var="_contact" varStatus="idx">
...
<p:autoComplete value="#{orderItem.contacts[idx.index]}"
id="existingContact"
binding="#{contactGroupManager.contactAutoComplete}"
converter="#{baseEntityConverter}"
completeMethod="#{contactGroupManager.autocomplete}"
forceSelection="true"
var="row" itemValue="#{row}" itemLabel="#{row.toString()}"
minQueryLength="2"
maxResults="10"
>
<f:attribute name="orderItem" value="#{orderItem}" />
</p:autoComplete>
The signature of the complete method is...
public List<Contact> autocomplete(Object suggest) {
}
And the converter follows Bauke Scholtz pattern for entities:
Implement converters for entities with Java Generics
As defined above, the value of orderItem.contacts[idx.index] is being set to a string, corresponding to the toString() of the selected pojo. The converter is never called.
If I change the value to a property of class Contact on another backing bean, the converter is called and the property is set to the selected Contact entity. This is the correct behavior.
value="#{contactSelector.selectedContact}"
Is it possible that autoConverter is not picking up the entity class from the List, and are there any suggested workarounds for this?

How store label in select menu to bean and populate in input text field [duplicate]

I am working on a JSF page which has a dropdown based on List<SelectItem>:
<h:selectOneMenu value="#{bean.selectedItem}">
<f:selectItems value="#{bean.availableItems}" />
</h:selectOneMenu>
I need to get both the value and label of the currently selected item. Right now I only get the value. How can I get the label, too?
You can't. That's just how HTML works. You know, JSF is a HTML code generator. The JSF <h:selectOneMenu> generates a HTML <select><option> . The HTML <select> element will only send the value attribute of the selected <option> element. It will not send its label.
But that shouldn't be a big issue. You namely already know both the value and label in the server side, inside the #{bean.availableItems}. All you need to do to get the associated label is to get it by the value as key. I suggest to make it a Map which in turn can also be used in f:selectItems.
Basic kickoff example:
public class Bean {
private String selectedItem; // +getter +setter
private Map<String, String> availableItems; // +getter
public Bean() {
availableItems = new LinkedHashMap<String, String>();
availableItems.put("value1", "label1");
availableItems.put("value2", "label2");
availableItems.put("value3", "label3");
}
public void submit() {
String selectedLabel = availableItems.get(selectedItem);
// ...
}
}
with
<h:selectOneMenu value="#{bean.selectedItem}">
<f:selectItems value="#{bean.availableItems.entrySet()}" var="entry"
itemValue="#{entry.key}" itemLabel="#{entry.value}" />
</h:selectOneMenu>
and in result
<p>Selected label is #{bean.availableItems[bean.selectedItem]}</p>
An alternative is to wrap both name and value in a javabean object representing an entity and set the whole object as value, via a converter.
See also:
Our selectOneMenu wiki page
How to populate options of h:selectOneMenu from database?
Instead of Using Map I tried like this and it's perfectly working for me to get both ItemValue and ItemLabel in the same property by using "ItemValue" attribute in selectItems tag.How ever provided no extra commas in the ItemLabel(#asfas....i had the same problem u mentioned so i selected this approach).
<h:selectOneMenu value="#{company.issueDesc}" required="true" onchange="submit()">
<f:selectItem itemLabel="-- Select a Issue -- " itemValue="0"/>
<f:selectItems value="#{company.issueList}" var="model" itemLabel="#{model.IssueDesc}" itemValue="#{model.Code},#{model.IssueDesc}" >
</f:selectItems>
</h:selectOneMenu>
Basically IssueDesc is String type in Bean Company
public Class Company{
private String issueDesc; // getters and setters
private int code; // getters and setters
private List<T>issueList; // getters and setters.
public void getLblandVal(){
String desc=getIssueDesc();
String[] str_ary=desc.split(",");
String s1=str_ary[0];
String s2=str_ary[1];
// parse **s1** to int;
}
}
What if the the value should be Integer and label String and both are needed in backing bean. Using Map in bean doesn't work because JSF interprets the map key as label. Ideally it would be a LinkedHashMap and search the text by a number.
Seems upside down to search number (value) by a text (key). What if some implementation of JSF adds extra space to test or letter case changes for some reason. Then the value is not found from map.
This will do the trick.
private String getLabel(List<SelectItem> list, String selection) {
String label = "";
for (int i = 0; i < list.size(); i++) {
if(selection.equals((String)list.get(i).getValue())) {
label = (String)list.get(i).getLabel();
break;
}
}
return label;
}
In your example, you would pass in the availableItems as 'list' and selectedItem as 'selection'. This method will return the label value corresponding to the selectedItem.
The following approach may also be useful in getting value and label using List <SelectItem>:
Here, facade, statesFacade fetches list of states from database/enterprise bean.
In view (xhtml page):
<h:selectOneMenu id="statesSelectUi" value="#{applicationBean1.state}">
<f:selectItems value="#{applicationBean1.stateSelectItems}"/>
<f:ajax render="selectedItem" event="change" execute="statesSelectUi"/>
</h:selectOneMenu>
<br/>
<br/>
<h:outputText id="selectedItem" value="#{applicationBean1.selectedState}"/>
In the Managed Bean(applicationBean1.java):
private String state;
/**
* #return the stateSelectItems
*/
public List<SelectItem> getStateSelectItemsItems() {
stateSelectItems.add(new SelectItem("-1","--- Select state ---"));
int statesCount = statesFacade.count();
List<StateSelectItems> states;
states = statesFacade.findAll();
for (int i = 0; i < statesCount; i++) {
stateSelectItems.add(new SelectItem(states.get(i).getStateSlNo(), states.get(i).getStateName()));
}
return stateSelectItems;
}
public String getSelectedState(){
if("".equals(getState()) || getState() ==null){
return "";
}else{
return "Selected State : " + getStateSelectItems.get(Integer.parseInt(getState())).getValue()+", "++ getStateSelectItems.get(Integer.parseInt(getState())).getLabel();
}
}

How to set defalult selected items in selectOneRadio/selectCheckboxMenu by beans in primefaces

I want to create selectOneRadio list and selectCheckboxMenu which items get from related bean objects.
For non selected list it is working well.But how can i provide these lists with some item(s) selected by default.
My current selectCheckboxMenu code is like this.
<p:selectCheckboxMenu id="trdays"
value="#{mybean.selectedDay}"
label="Select Days">
<f:selectItems value="#{mybean.dayList}" var="day"
itemValue="#{day.value}" itemLabel="#{day.name}"/>
</p:selectCheckboxMenu>
it should look like this when page loaded and user haven't done anything yet.
EDIT
Day Class :-
public class Day{
private String name;
private String value;
//getters and setters
}
Value attribute of selectCheckboxMenu component should get the your default values.
On bean side you should write a getter for selectedDayList and all daylist.
Example:
#PostConstruct
public void init() {
dayList= new ArrayList<String>();
dayList.add("Mon");
dayList.add("Tue");
dayList.add("Wed");
dayList.add("Thu");
dayList.add("Fri");
dayList.add("Sat");
dayList.add("Sun");
selectedDayList= new ArrayList<String>();
selectedDayList.add("Tue");
selectedDayList.add("Wed");
}
public List<String> getDayList()
{
return dayList;
}
public List<String> getSelectedDaylist()
{
return selectedDayList;
}
.xhtml page should be like this.
<p:selectCheckboxMenu id="trdays"
value="#{mybean.selectedDaylist}"
label="Select Days">
<f:selectItems value="#{mybean.dayList}" var="day"
itemValue="#{day.value}" itemLabel="#{day.name}"/>
</p:selectCheckboxMenu>
Good Luck!
Just add default values in the selectedDay list (or array) in init method (with #PostConstruct annotation). These values should have same value as corresponding itemValue attribute (in your case this is day.value).

How to preselect an option of h:selectOneMenu

Is it possible to preselect one of the options from the select menu?
I have this UI Component:
<h:selectOneMenu value="#{authenticateController.country}">
<f:selectItems value="#{constants.countrySelectMenu}" />
</h:selectOneMenu>
The values of #{constants.countrySelectMenu} are a list of country ID - country name pairs.
Is there a way to render the list with a preselected value or at least is there a work-around to get this done?
Just preset the property behind <h:selectOneMenu value> with the desired value. You can do it in for example the bean's (post)constructor, action(listener) method, etc.
In your specific example, thus e.g.
public class AuthenticateController {
private String country;
#PostConstruct
public void init() {
country = "NL";
}
// ...
}
It works exactly the same way for all other UIInput components like <h:inputText> and so on. The input component's value itself simply represents the (pre)selected/checked/filled value.
See also:
How to populate options of h:selectOneMenu from database?

Resources