开发者

How to populate a dropdown on page load in jsf? [duplicate]

This question already has answers here: How to populate options of h:selectOneMenu from database? (5 answers) 开发者_开发问答 Closed 6 years ago.

I'm new to JSF, I read the JSF life cycle but couldn't understand how to achieve this?

I've a controller say "Cities" and other controller "Countries". Now I'm going to create a new page, where I will provide search functionality. I showed two dropdowns on that page (One for countries and other for cities), I want the first drop down to be populated on page load. Please tell me which controller to use? Cities/Countries? or create a new one? and How to load data on page load?

Thanks!


Everyone is correct, you need to use <f:selectItems/>

Example:

.Xhtml

<h:selectOneMenu>
    <f:selectItems value="#{myController.listItems}"/>
</h:selectOneMenu>

Bean

public class MyController{
    //The list with the items
    private List<SelectItem> listItems = null;

    public MyController {
        loadCombo();
    }

    (...)

    //Loading the items
    private void loadCombo() {
        listItems = new ArrayList<SelectItem>();

        //You can do with BD data using a for. How to add a new item:
        //listItems.add(new SelectItem("itemValue", "itemLabel"));

        listItems.add(new SelectItem("1", "Item 1"));
        listItems.add(new SelectItem("2", "Item 2"));
        listItems.add(new SelectItem("3", "Item 3"));
        listItems.add(new SelectItem("4", "Item 4"));
    }

    (...)

    //Getters and setters
}

Do not populate the list in a "get" method, because JSF will call it more than once and it will kill your performance.


It is preferable to use one controller for the page which will hold collections of Countries and Cities. To load the countries on page load you should create a method annotated with @Postconstruct. In this method you do your initialization. i.e.

@PostConstruct
public void init(){
     //do your initialization
}


Countries is most likely a static collection, so you can just create an application scoped bean with a static Map that holds the countries (key country name, value country code).

Then simply bind your <f:selectItems> in every view that needs a country drop-down to that.

(credits to BalusC btw for this solution ;))


In your controller you need getter public List<SelectItem> getFirmaTyp() and then in your view you should have something like next.

<h:selectOneMenu value="#{yourController.firma.typ.id}">
   <f:selectItems value="#{yourController.firmaTyp}" />
</h:selectOneMenu>

Getters are called everytime the page is displayed. In my example On postback the id for dropDown is set to entity firm type and id like yourController.firma.typ.id

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜